简体   繁体   English

从文本文件读入ListBox

[英]Read from text file into ListBox

I want to read the values of each rows in a textfile to a ListBox control. 我想将文本文件中每一行的值读取到ListBox控件中。 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());
    }
}

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: 顺便说一句,您将需要在aspx页面中执行以下操作:

    <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>

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 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. 但是,用户将必须指向该文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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