我想阅读一个文本文件,其中包含多个以新行分隔的段落。如何在RichTextBox
中单独阅读每个段落,以及如何通过按钮接下来转移到下一个段落,然后按照之前在表单中设计的按钮返回到第一个段落。我的代码
private void LoadFile_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
dialog.Title = "Select a text file";
dialog.ShowDialog();
if (dialog.FileName != "")
{
System.IO.StreamReader reader = new System.IO.StreamReader(dialog.FileName);
string Text = reader.ReadToEnd();
reader.Close();
this.Input.TextChanged -= new System.EventHandler(this.Input_TextChanged);
Input.Clear();
Input.Text = Text;
}
}
答案 0 :(得分:3)
使用此代码。
var text = File.ReadAllText(inputFilePath);
var paragraphs = text .Split('\n');
段落将是包含所有段落的字符串数组。
答案 1 :(得分:0)
使用String.split()
将其拆分为'\n'
。
然后在Button next 上遍历数组。
private string[] paragraphs;
private int index = 0;
private void LoadFile_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter =
"txt files (*.txt)|*.txt|All files (*.*)|*.*";
dialog.Title = "Select a text file";
dialog.ShowDialog();
if (dialog.FileName != "")
{
System.IO.StreamReader reader = new System.IO.StreamReader(dialog.FileName);
string Text = reader.ReadToEnd();
reader.Close();
this.Input.TextChanged -= new System.EventHandler(this.Input_TextChanged);
Input.Clear();
paragraphs = Text.Split('\n');
index = 0;
Input.Text = paragraphs[index];
}
}
private void Next_Click(object sender, EventArgs e)
{
index++;
Input.Text = paragraphs[index];
}
(我知道这可能不是最优雅的解决方案,但应该知道该怎么做。)