循环通过FileUpload控件上传的txt文件行

Per*_*ddy 9 c# asp.net upload file-upload filestream

我想使用FileUpload控件选择一个包含字符串行的简单.txt文件.但不是实际保存文件,而是想循环遍历每行文本并显示ListBox控件中的每一行.

文本文件示例:

的test.txt

123jhg345
182bdh774
473ypo433
129iiu454

完成此任务的最佳方法是什么?

到目前为止我所拥有的:

private void populateListBox()
{
  FileUpload fu = FileUpload1;

  if (fu.HasFile)
  {
    //Loop trough txt file and add lines to ListBox1
   }
 }
Run Code Online (Sandbox Code Playgroud)

620*_*2SP 17

private void populateListBox() 
{
    FileUpload fu = FileUpload1; 
    if (fu.HasFile)  
    {
        StreamReader reader = new StreamReader(fu.FileContent);
        do
        {
            string textLine = reader.ReadLine();

            // do your coding 
            //Loop trough txt file and add lines to ListBox1  

        } while (reader.Peek() != -1);
        reader.Close();
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 8

这是一个有效的例子:

using (var file = new System.IO.StreamReader("c:\\test.txt"))
{
    string line;
    while ((line = file.ReadLine()) != null)
    {
        // do something awesome
    }
}
Run Code Online (Sandbox Code Playgroud)


Car*_*ten 5

将文件打开到StreamReader并使用


while(!reader.EndOfStream) 
{ 
   reader.ReadLine; 
   // do your stuff 
}
Run Code Online (Sandbox Code Playgroud)

如果您想知道如何将文件/日期转换为流,请说明以何种形式获取文件(s字节)