'How save a entire text file to a array and display in textbox
string[] readText = File.ReadAllLines(path);
foreach (string s in readText)
{
textBox1.Text = string.Join(",",s);
}
This is what is in the text file:
10,
1,2,3,4,5,
6,76,81,9
in the text box in visual studio it only displays the last line, i am trying to make it display everything
Solution 1:[1]
You have to append to the text box, not just assign it. Note the plus.
textBox1.Text += string.Join(",",s);
When your text file has lots of rows, the above method will not be good, since it will do lot of memory re-allocations, instead you can use the StringBuilder as in other answer.
Alternately, since you already got all the lines present in your text file into the array named readText, you just need to do this, without need for a foreach loop.
textBox1.Text = string.Join(Environment.NewLine, readText);
Solution 2:[2]
First lets understand with your current approach why only the last line is displayed in the textBox1?
You are iterating over each line and assigning the same to
textBox1.Text. You are not storing previous lines any where, so in every iteration previous data get replaced with new line data.foreach (string s in readText) { textBox1.Text = string.Join(",",s); //Assigning new data everytime. }
This is the reason, after the execution foreach loop, only last line data is displayed.
Solution:
Now lets see how can we fix it,
Instead of assigning each line to textBox1, store entire data into a StringBuilder object and finally assign it to textBox1.
string[] readText = File.ReadAllLines(path);
StringBuilder sb = new StringBuilder();
foreach (string s in readText)
{
sb.AppendLine(string.Join(",",s));
}
textBox1.Text = sb.ToString();
If the data is already comma separated in the text file then you just need to join each link by \n, we do not require string.Join(',', s) again inside foreach loop,
textBox1.Text = string.Join(@"\n", readText);
Solution 3:[3]
You would need to append the subsequent text to the current value you have, but not reassign.
Also remember to set your Textbox Multiline Property to True to display all text.
public Form1()
{
InitializeComponent();
string[] readText = File.ReadAllLines(@"C:\testfile.txt");
int counter = 0;
foreach (string s in readText)
{
if (counter == 0)
{
textBox1.Text = string.Join(",", s);
}
else
{
textBox1.Text = textBox1.Text + string.Join(",", s);
}
textBox1.AppendText(Environment.NewLine);
counter++;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Dharman |

