Reputation: 281
I use this code to read every line from my file but it only reads (or it only displays the last line of the file). When i open the file in notepad i can see that there are more than one lines. Here's the code that i am using:
using (StreamReader sr = File.OpenText(newPath))
{
String input;
while ((input = sr.ReadLine()) != null)
{
TextBox1.Text = input;
}
Upvotes: 3
Views: 2151
Reputation: 9394
I would prefer a stringbuilder for several reasons. The main advantage of using a string-builder is that it costs lower resources to manipulate strings.
The usage of a StringBuilder looks like:
StringBuilder builder = new StringBuilder();
using (StreamReader sr = File.OpenText(newPath)) {
while ((input = sr.ReadLine()) != null) {
builder.AppendLine(input);
}
}
TextBox1.Text = builder.ToString();
Upvotes: 0
Reputation: 3994
Each iteration of your while loop replaces the previous value of TextBox1.Text with the line it has read, so when the loop ends, you've simply updated the Text propery with the last line in the file.
Consider using File.ReadAllText() in place of a line-by-line read.
TextBox1.Text = File.ReadAllText(newPath);
Upvotes: 6
Reputation: 5435
Your code is almost correct, but the line :
TextBox1.Text = input;
Overwrites TextBox1 with "input", replacing whatever was in it previously. You are instead looking to append your text. So, you want:
TextBox1.Text += input + "\n";
This will "add" each line to the text box, and put a new-line in between each one to replace the one you got rid of when you grabbed a line using readLine().
Upvotes: 1
Reputation: 30615
If you want to use each line of data separately you need an extra string variable to assign each line to because for every line in the file you iterate through, you're over-writing "input", leaving it with the value of the last line.
Upvotes: 0
Reputation: 1885
You need to use:
TextBox1.Text += input;
else the described behaviour is correct
eventually you can change your sample as:
String input;
String target = String.Empty;
try {
using (StreamReader sr = File.OpenText(newPath))
{
while ((input = sr.ReadLine()) != null)
{
target += input;
}
}
TextBox1.Text = target;
} catch { ... }
and the best would be to extract the reading process to a separate method..
Upvotes: 4