2015-04-06 48 views
-1

我有一個平面文件,我在C#中閱讀並嘗試解析。我的意思是將帳號存儲在數組中的平面文件中。拆分數組並在while循環中添加到新數組中

AccountNumber | AccountName | DateCreated 
1    | Bob   | 1/1/2011  
2    | Donna  | 3/2/2013  
3    | Jake  | 2/21/2010 
5    | Sally  | 4/2/2014  

到目前爲止,這是我的分裂的樣子:

//List<string[]> myArrayList = new List<string[]>(); 
using (StreamReader read = new StreamReader(@"C:\text\Accounts.txt")) 
      { 
       string line; 
       while ((line = read.ReadLine()) != null) 
       { 
        string[] parts = line.Split('|'); 
        Console.WriteLine(parts[0]); 
        //myArrayList.Add(parts[0]); 
       } 
      } 

我如何存儲集團的印刷份數[0]在它自己的陣列while循環外的一切嗎?我試着做一個列表添加,但我不斷收到錯誤的無效參數。我評論了那些不起作用的位。

+3

你的'myArrayList'是錯誤的數據類型。 'parts [0]'將返回一個'string',而不是'string []'。 – krillgar

+1

是否有一個原因,你不一次閱讀所有的文本一起分裂文件..?你甚至可以通過創建一個與文件結構相同的類並將數據保存到您創建的列表中來更好地做到這一點... – MethodMan

+1

@krillgar我修復了我的數據類型,現在它按預期工作! – KillerSmalls

回答

1

下面的代碼讀取文件中的內容,分割線,將其存儲在一個列表最後在RichTextBox中顯示第一列

private void button1_Click(object sender, EventArgs e) 
    { 
     List<string[]> myArrayList = new List<string[]>(); 
     StreamReader read = new StreamReader(@"C:\test\Accounts.txt"); 

     string line; 
     while ((line = read.ReadLine()) != null) 
     { 
      string[] parts = line.Split('|'); 
      //Console.WriteLine(parts[0]); 
      myArrayList.Add(parts); 
     } 

     foreach (var account in myArrayList) 
     { 
      richTextBox1.Text = richTextBox1.Text + account[0].ToString() + Environment.NewLine; 
     } 
    } 

enter image description here

0

我喜歡MethodMan的建議:

// Class structure 
public class Account 
{ 
    public int AccountNumber; 
    public string AccountName; 
    public DateTime DateCreated; 

    public Account(string[] info) 
    { 
     // This is all dependent that info passed in, is already valid data. 
     // Otherwise you need to validate it before assigning it 
     AccountNumber = Convert.ToInt32(info[0]); 
     AccountName = info[1]; 
     DateCrated = DateTime.Parse(info[2]); 
    } 
} 

使用類結構您的代碼:

List<Account> myAccounts = new List<Account>(); 
using (StreamReader read = new StreamReader(@"C:\text\Accounts.txt")) 
{ 
    string line; 
    while ((line = read.ReadLine()) != null) 
    { 
     string[] parts = line.Split('|'); 
     myAccounts.Add(new Account(parts)); 
    } 
} 

// Do whatever you want after you have the list filled