rickyProgrammer
rickyProgrammer

Reputation: 1167

Read textfile and count number of Lines into Textbox using ASP.NET C#

My objective is to read the textfile, manipulate the contents and display the result inside a listbox or listview

For example, a textfile has a content of multiple line grouped per date. What I need is to display the number of lines the textfile has into textbox

here's the sample textfile

enter image description here

What I only have is to read the textfile using fileupload, button and Listbox and display all the content in it

 protected void btnRead_Click(object sender, EventArgs e)
    {

        using (StreamReader stRead = new StreamReader(FileUpload1.PostedFile.InputStream))
        {
            //to write textfile content
            while (!stRead.EndOfStream)
            {
                ListBox1.Items.Add(stRead.ReadLine());
            }
        }



    }

1. What can I do to count the lines in the textfile and display in textbox instead of listbox?

Upvotes: 0

Views: 949

Answers (1)

M. Wiśnicki
M. Wiśnicki

Reputation: 6203

Add TextBox with TextMode="MultiLine" :

<asp:TextBox ID="multitxt" runat="server" TextMode="MultiLine" ></asp:TextBox>

Code behind:

string text = String.Empty;
using (StreamReader stRead = new StreamReader(FileUpload1.PostedFile.InputStream))
{
     int i = 0;
     //to write textfile content
     while (!stRead.EndOfStream)
     {
       text+=stRead.ReadLine()+Environment.NewLine;
       i++;
     }

 }

multitxt.Text = text;

i give you number of lines in txt file

You can always get number of lines

var file = stRead.ReadToEnd(); 
var allLines= file.Split(new char[] {'\n'});           
var count= lines.Count;

Or from TextBox

this.multitxt.Text.Split(new Char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length;

Upvotes: 1

Related Questions