Reputation: 21
good morning, I'm having trouble with the following. I'm reading the contents of a file (. txt) in a folder, but what I want now is to print the contents of the files into a textbox, but I'm having problems with that.
what I have to code this is.
FolderBrowserDialog Lectura = new FolderBrowserDialog();
DialogResult response = Lectura.ShowDialog();
if (response == DialogResult.OK)
{
string[] files = Directory.GetFiles(Lectura.SelectedPath);
ListBox archivosListBox = new ListBox();
archivosListBox.Items.AddRange(files);
int tamanoLista = archivosListBox.Items.Count;
List <string[]> Miarchivo = new List<string[]>();
foreach (string archivos in archivosListBox.Items)
{
Miarchivo.Add(System.IO.File.ReadAllLines(archivos));
}
string[] leerArchivo;
int j =Miarchivo.Count;
for (int i = 0; i<tamanoLista; i++)
{
leerArchivo = Miarchivo[i];
for (int k = 0; k < Miarchivo[i].Count(); k++)
{
//textBox1.Text += leerArchivo[k] ;
}
}
}
Upvotes: 0
Views: 1420
Reputation: 236328
Use ReadAllText
instead of ReadAllLines
and replace entire loop with string join:
List<string> Miarchivo = new List<string>();
foreach (string archivos in archivosListBox.Items)
Miarchivo.Add(File.ReadAllText(archivos));
textBox1.Text = String.Join(Environment.NewLine, Miarchivo);
Another (probably better solution) is usage of TextBox.Lines
property and getting files content with LINQ:
textBox1.Lines = archivosListBox.Items
.Cast<string>()
.SelectMany(archivos => File.ReadLines(archivos))
.ToArray();
Upvotes: 3
Reputation: 152654
Based on your comments it sounds like you just need a line break at the end of each line:
textBox1.Text += leerArchivo[k] + Environment.NewLine ;
Upvotes: 0
Reputation: 186843
You'd rather update textBox1.Text
once in order to avoid constant repainting:
if (response == DialogResult.OK)
{
string[] files = Directory.GetFiles(Lectura.SelectedPath);
ListBox archivosListBox = new ListBox();
archivosListBox.Items.AddRange(files);
int tamanoLista = archivosListBox.Items.Count;
List <string[]> Miarchivo = new List<string[]>();
foreach (string archivos in archivosListBox.Items)
{
Miarchivo.Add(System.IO.File.ReadAllLines(archivos));
}
// Output into textBox1
StringBuilder sb = new StringBuilder();
foreach(String[] leerArchivo in Miarchivo)
foreach(String item in leerArchivo) {
if (sb.Length > 0)
sb.AppendLine(); // <- Or other deriver, e.g. sb.Append(';');
sb.Append(item);
}
// Pay attention: textBox1 has been updated once only
textBox1.Text = sb.ToString();
}
Upvotes: 1
Reputation: 14432
You need to place a newline character after each entry in your TextBox. Change your code to following:
for (int k = 0; k < Miarchivo[i].Count(); k++)
{
textBox1.Text += leerArchivo[k] + Environment.NewLine;
}
More reading: Environment.NewLine Property (MSDN).
Upvotes: 3