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

Time:10-14

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.

CodePudding user response:

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.

CodePudding user response:

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 .

  • Related