My Textfile looks like this:
(-*-)
textA1
textA2
textA3
(-*-)
textB1
textB2
textB3
(-*-)
textC1
...
Now i try to get the Textfile split up by the (-*-)
string (<-it´s always this in the Textfile!) and show it in different richtextboxes.
I use actually following Code...
Tried with datatable, stringbuilder, iList...
My Goal is to get all textA in richtextbox A, textB in richtextbox B and so on...
private void öffnenToolStripMenuItem_Click(object sender, EventArgs e)
{
var seiten = new List<string>();
if (oFDOpenDatei.ShowDialog() == DialogResult.OK)
{
using (StreamReader sr = new StreamReader(oFDOpenDatei.FileName))
{
while (!sr.EndOfStream)
{
string[] read = sr.ReadLine().Split(new string[] { "(-*-)" }, StringSplitOptions.None);
for (int i = 0; i < read.Length; i++)
{
seiten.Add(Convert.ToString(read));
}
//foreach (var item in read)
//{
// seiten.Add(Convert.ToString(item));
//}
}
sr.Close();
}
rTBA.Text = seiten[0][0].ToString();
rTBB.Text = seiten[1][0].ToString();
}
}
-the activ "for" statment shows a "S" in both richtboxes ... for whatever reason :))
-the foreach says out of index, but when i check the array.lenght, it shows me 1 at A and 2 at B ... not more
can someone please get me on the right track!?
First of all, it looks like you want your list to contain array-of-string elements, not string elements. In this case, it should be of type List<string[]>
.
Second, when you use ReadLine()
, it returns only one line. If you wish to split based on a specific line, you need to read multiple lines.
Here's an easy solution with LINQ:
var seiten = new List<string[]>();
var allLines = File.ReadAllLines(oFDOpenDatei.FileName);
int consumedLines = 0;
while (consumedLines < allLines.Length)
{
var group = allLines.Skip(consumedLines).TakeWhile(s => s != "(-*-)").ToArray();
if (group.Any()) seiten.Add(group);
consumedLines += group.Length + 1;
}
If you don't need access to individual lines of the same group, then you can still use a List<string>
and adjust the above code to something like this:
var seiten = new List<string>();
var allLines = File.ReadAllLines(oFDOpenDatei.FileName);
int consumedLines = 0;
while (consumedLines < allLines.Length)
{
var group = allLines.Skip(consumedLines).TakeWhile(s => s != "(-*-)").ToArray();
if (group.Any()) seiten.Add(string.Join(Environment.NewLine, group));
consumedLines += group.Length + 1;
}
rTBA.Text = seiten[0];
rTBB.Text = seiten[1];