Looping through lines of txt file uploaded via FileUpload control

青春壹個敷衍的年華 提交于 2019-12-03 13:22:56
62071072SP
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();
    }
}

Here's a working example:

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

open the file into a StreamReader and use


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

If you want to know how to get the file/date into a stream please say in what form you get the file(s bytes)

There are a few different ways of doing this, the ones above are good examples.

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

There is this as well, using HttpPostedFileBase in MVC:

[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;//
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.... 
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!