Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从文本文件读入列表框_C#_Asp.net_Visual Studio 2008 - Fatal编程技术网

C# 从文本文件读入列表框

C# 从文本文件读入列表框,c#,asp.net,visual-studio-2008,C#,Asp.net,Visual Studio 2008,我想将文本文件中每行的值读取到ListBox控件。 文件需要上传到客户端 我有从固定文件读取的代码,但我不知道如何上传文件然后从中读取 从普通文件读取的代码为: protected void Button1_Click(object sender, EventArgs e) { FileInfo file = new FileInfo("file"); StreamReader stRead = file.OpenText(); while (!stRead.EndOfS

我想将文本文件中每行的值读取到ListBox控件。 文件需要上传到客户端

我有从固定文件读取的代码,但我不知道如何上传文件然后从中读取

从普通文件读取的代码为:

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());
    }
}

要从客户端获取文件,必须使用文件上载控件


文件上载有一个文件流,您可以从中读取。但是,用户必须指向该文件。

如果我是你,我会这样做。希望这有帮助

    protected void btnUpload_Click(object sender, EventArgs e)
{
    using (StreamReader stRead = new StreamReader(FileUpload1.PostedFile.InputStream))
    {
        while (!stRead.EndOfStream)
        {
            ListBox1.Items.Add(stRead.ReadLine());
        }
    }
}
顺便说一句,您需要在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>


那么您的问题实际上是“如何上传文件”?是的,但我不想将文件保存在数据库中。只需阅读它并从中获取值。是否需要将文件保存到某个位置?不太清楚您的意思,但您可以执行类似ListBox1.Items[0]的操作。Text=“随便”;我的意思是用户可以编辑列表框中的值(从文件中)。。。与更改名称类似。您不能直接从列表框中编辑它。您必须先将所选列表项的文本加载到文本框中进行编辑,然后将列表项的文本属性设置为textbox.text。这只会更新列表,但不会更新文件。还有一件事。。。该代码适用于.txt文件,而不适用于.doc和excel文件。你能帮我吗