我有这段代码
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
}
}
}
我正在努力研究如何将文本文件的每一行放到另一个文本框中,或者可能将它存储在一个数组中,有人可以帮忙!
答案 0 :(得分:3)
File.ReadAllText将读取文件中的所有文字。
string filetext = File.ReadAllText("The file path");
如果你想将每一行分别存储在一个数组中,File.ReadAllLines可以做到这一点。
string[] lines = File.ReadAllLines("The file path");
答案 1 :(得分:1)
或者,您可以使用以下命令返回字符串列表。然后,您可以将字符串列表直接绑定到控件,也可以遍历列表中的每个项目并以这种方式添加它们。见下文:
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;
}