2011-08-22 91 views
7

我想選擇一個簡單的.txt文件,其中包含使用FileUpload控件的字符串行。但不是實際保存文件,我想循環每行文本,並在ListBox控件中顯示每行。通過FileUpload控件上傳txt文件的循環槽線

一個文本文件的例子:

的test.txt

123jhg345
182bdh774
473ypo433
129iiu454

什麼是實現這一目標的最佳方式是什麼?

我到目前爲止有:

private void populateListBox() 
{ 
    FileUpload fu = FileUpload1; 

    if (fu.HasFile) 
    { 
    //Loop trough txt file and add lines to ListBox1 
    } 
} 

回答

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

感謝Shalini, 這就是我一直在尋找。請注意,流讀取器需要初始化爲: ** StreamReader reader = new StreamReader(fu.PostedFile.InputStream); ** – PercivalMcGullicuddy

+0

感謝您的朋友。你救了我的一天。 –

4

打開該文件爲StreamReader和使用


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

如果你想知道如何得到的文件/日期到流,請說,在什麼形式你得到的文件(s字節)

8

這裏有一個工作示例:

using (var file = new System.IO.StreamReader("c:\\test.txt")) 
{ 
    string line; 
    while ((line = file.ReadLine()) != null) 
    { 
     // do something awesome 
    } 
} 
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(); 
} 
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;// 
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.... 
     } 
    } 
}