I’m building a website in ASP.net and, in this case, I’m simply trying to read a .txt file and output it into a textbox whenever that page loads. I wrote this code so I could execute my idea:
protected void Page_Load(object sender, EventArgs e)
{
foreach (string line in System.IO.File.ReadLines(@"file_path"))
{
TextBox1.Text = line;
}
}
However, this is not working, as when I execute the website on this page, nothing loads. There is no exception that is being called or any error.
What can I do?
If you need more details or information, please don’t refrain from asking.
Edit: I think it’s important to say that I’ve tested doing
TextBox1.Text = "Hello World";
And that worked properly.
2
Answers
To read the first line, you can simply write this
File.ReadLines(“YourFileName”).FirstOrDefault;
You need to use the method File.ReadAllText. It reruns the
string
value. And you can then assign toText
property.File.ReadLines returns
Ienumerable<string>
notstring
.Well, to read the text, this works:
And if some some reason, you LEFT OUT some HUGE MASSIVE WHOPPER detail, say like you only want the first line of text from the file?
Then this:
FYI:
Don’t forget to set the text box to multiline if you need/want to have more then one line of text display in that box.
As pointed out, we can use this:
however, the above still reads the whole text file.
If the text file is to be large, and we still want the first line, or wish to read + process line by line, then this is better:
So, above would read line by line, and if the text file was large, or we wish to only pull + read the first line from the file? Then of course the above example is better, since only the first line (or several lines if i condition is changed) is better from a performance + io point of view.