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

时间:2011-08-22 15:43:30

标签: c# asp.net file-upload 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
   }
 }

6 个答案:

答案 0 :(得分:16)

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

答案 1 :(得分:8)

这是一个有效的例子:

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

答案 2 :(得分:5)

将文件打开到StreamReader并使用


while(!reader.EndOfStream) 
{ 
   reader.ReadLine; 
   // do your stuff 
}

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

答案 3 :(得分:3)

有几种不同的方法可以做到这一点,上面的例子很好。

string line;
string filePath = "c:\\test.txt";

if (File.Exists(filePath))
{
   // Read the file and display it line by line.
   StreamReader file = new StreamReader(filePath);
   while ((line = file.ReadLine()) != null)
   {
     listBox1.Add(line);
   }
     file.Close();
}

答案 4 :(得分:0)

还有这个,在MVC中使用HttpPostedFileBase:

[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{    
    if (file != null && file.ContentLength > 0)
    {
          //var fileName = Path.GetFileName(file.FileName);
          //var path = Path.Combine(directory.ToString(), fileName);
          //file.SaveAs(path);
          var streamfile = new StreamReader(file.InputStream);
          var streamline = string.Empty;
          var counter = 1;
          var createddate = DateTime.Now;
          try
          {
               while ((streamline = streamfile.ReadLine()) != null)
               {
                    //do whatever;//

答案 5 :(得分:0)

private void populateListBox()
{            
    List<string> tempListRecords = new List<string>();

    if (!FileUpload1.HasFile)
    {
        return;
    }
    using (StreamReader tempReader = new StreamReader(FileUpload1.FileContent))
    {
        string tempLine = string.Empty;
        while ((tempLine = tempReader.ReadLine()) != null)
        {
            // GET - line
            tempListRecords.Add(tempLine);
            // or do your coding.... 
        }
    }
}