2011-08-22 9 views
7

FileUploadコントロールを使用して文字列を含む単純な.txtファイルを選択したいとします。しかし、実際にファイルを保存する代わりに、各行のテキストをループさせ、各行を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 
} 

を使用します。私がこれまで持っているもの

あなたはファイルをどのような形式で取得しますか?

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.... 
     } 
    } 
} 
関連する問題