2017-04-09 49 views
0

我不知道我需要放入這個while循環(或者如果有更好的方法來做到這一點),以便將itemsListBox中的所有項目添加到文件中。現在(在writer.writeline之前沒有任何while循環)它只將最後一項添加到文件中。該程序應該將項目添加到列表框並將其保存到文件中,然後在重新打開程序時加載它們。它還有一個跟蹤列表框中項目數量的標籤。添加多個項目到一個文件

private const string TO_DO_LIST = "to-do-list.txt"; 
public Form1() 
{ 
    InitializeComponent(); 
} 

private void enterButton_Click(object sender, EventArgs e) 
{ 
    AddItem();    
} 

private void AddItem() 
{ 
    itemsList.Items.Add(itemsBox.Text); 
    numberOfItemsLabel.Text = itemsList.Items.Count.ToString(); 
    SaveItem();   
} 

private void SaveItem() 
{ 
    StreamWriter writer = File.CreateText(TO_DO_LIST); 
    string newItem = itemsBox.Text; 

    while()//??? 
    { 
     writer.WriteLine(newItem); 
    } 

    writer.Close(); 
} 

private void Form1_Load(object sender, EventArgs e) 
{ 
    try 
    { 
     StreamReader reader = File.OpenText(TO_DO_LIST); 
     while (!reader.EndOfStream) 
     { 
      itemsList.Items.Add(reader.ReadLine()); 
     } 
    } 
    catch (FileNotFoundException ex) 
    {    
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 
}  

回答

0

你可以只用一個使用File.AppendAllLines線,這將打開或創建一個文件,文本追加到它,並關閉它做到這一點。

第一個參數是文件路徑,第二個參數是要添加的行的IEnumerable

由於ListBox.ItemsListBox.ObjectCollection,我們需要將其轉換爲IEnumerable<string>才能使用AppendAllLines方法。這可以通過Cast<string>()方法來完成,結合ToList()

File.AppendAllLines(TO_DO_LIST, itemsList.Items.Cast<String>().ToList()); 
0

會這樣的工作嗎?

using (StreamWriter writer = File.CreateText(TO_DO_LIST)) 
{ 
    foreach (string text in itemsList.Items) 
    { 
     writer.WriteLine(text); 
    } 
}; 
+0

這在某種程度上並不能改變什麼,當然我想的東西很簡單 –

相關問題