0

I want to read the values of each rows in a textfile to a ListBox control. The file needs to be uploaded on the client side.

I have the code to read from a fixed file but I don't know how to upload a file and then read from it.

The code to read from a normal file is:

protected void Button1_Click(object sender, EventArgs e)
{
    FileInfo file = new FileInfo("file");
    StreamReader stRead = file.OpenText();
    while (!stRead.EndOfStream)
    {
        ListBox1.Items.Add(stRead.ReadLine());
    }
}
2
  • so is your question actually "how do I upload a file"??? Commented Sep 18, 2009 at 16:12
  • yes, but i dont want to save the file in my database. Just read it and take the values from it. Do i need to save the file somewhere ? Commented Sep 18, 2009 at 16:15

2 Answers 2

2

I would do it like this if I were you. Hope this helps!

    protected void btnUpload_Click(object sender, EventArgs e)
{
    using (StreamReader stRead = new StreamReader(FileUpload1.PostedFile.InputStream))
    {
        while (!stRead.EndOfStream)
        {
            ListBox1.Items.Add(stRead.ReadLine());
        }
    }
}

BTW you'll need this in the aspx page:

    <asp:FileUpload runat="server" ID="FileUpload1"/>
    <asp:Button ID="btnUpload" runat="server" onclick="btnUpload_Click" Text="Upload" />        
    <asp:ListBox runat="server" ID="ListBox1"></asp:ListBox>
Sign up to request clarification or add additional context in comments.

4 Comments

Not quite sure what you mean but you can do something like ListBox1.Items[0].Text = "Whatever";
i mean can a user edit the values in the listbox (from the file)... like change the name..
You can't edit it straight from the listbox you would have to load the selected listitem's text into a textbox first edit and then set the text property of the listitem to textbox.text. This would only update the list though not the file.
One more thing... The code works fine with .txt files bit not with the .doc and excel files. Can you help me with that
0

To get a file from the client side, you have to use a file upload control.

http://www.c-sharpcorner.com/UploadFile/mahesh/FileUpload10092005172118PM/FileUpload.aspx?ArticleID=79850d6d-0e91-4d7b-9e27-a64a09b0ee6b

The file upload has a stream of the file which you can read from. However the user will have to point to the file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.