简体   繁体   中英

How can I output text file's content line by line to a TextBox on ASP.NET?

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.

Well, to read the text, this works:

        string sFile = @"C:\TEST2\T.txt";
        string sTextData = File.ReadAllText(sFile);
        
        TextBox1.Text = sTextData;

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:

        string sFile = @"C:\TEST2\T.txt";
        string sTextData = File.ReadAllText(sFile);

        string strFirstLine = sTextData.Split(System.Environment.NewLine.ToCharArray())[0];

        TextBox1.Text = strFirstLine;

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:

  File.ReadAllLines(sFile).FirstOrDefault();

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:

            StreamReader sR = new StreamReader(sFile);
            int i = 0;
            while (!sR.EndOfStream)
            {
                i++;
                Debug.Print(i.ToString() + "->" + sR.ReadLine());
                if (i >= 1)
                    break;
            }
            sR.Close();

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.

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 to Text property.

File.ReadLines returns Ienumerable<string> not string .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM