读取文件内容到数组

read file contents to an array

我有这个代码

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

我正在为如何将文本文件的每一行放入不同的文本框或可能将其存储在一个数组中而苦苦挣扎,请有人帮忙!

您可以选择使用以下 return 字符串列表。然后您可以将字符串列表直接绑定到控件,或者您可以遍历列表中的每个项目并以这种方式添加它们。见下文:

public static List<string> GetLines(string filename)
{
    List<string> result = new List<string>(); // A list of strings 

    // Create a stream reader object to read a text file.
    using (StreamReader reader = new StreamReader(filename))
    {
        string line = string.Empty; // Contains a single line returned by the stream reader object.

        // While there are lines in the file, read a line into the line variable.
        while ((line = reader.ReadLine()) != null)
        {
            // If the line is not empty, add it to the list.
            if (line != string.Empty)
            {
                result.Add(line);
            }
        }
    }

    return result;
}

File.ReadAllText 将读取文件中的所有文本。

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

如果您想将每一行单独存储在一个数组中,File.ReadAllLines 可以做到。

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