2016-03-01 18 views
1
private void addServerButton_Click(object sender, EventArgs e) 
    { 
     serverListBox.Items.Add(this.serverTextBox.Text); 

     string path = @"C:\\Public Key Pin\UserServerData.txt"; 
     using (StreamWriter sw = File.CreateText(path)) 
     { 

      sw.Write(this.serverTextBox.Text); 
     } 
    } 

基本上我試圖使它所以什麼都被添加到「server'ListBox(使用文本框和按鈕)保存在一個文本,使用戶可以在他/她使用應用程序第二次「加載」服務器列表時,但是寫入列表框的內容將覆蓋文本文件中的前一項,因此,當用戶加載服務器列表(serverListBox)時,它只顯示一個項目(用戶添加到列表框的最後一個項目)。寫作行文本文件的幫助,Visual C#中

我該如何使它自動在文本文件中創建一個新行來停止項目被覆蓋?

回答

1

使用

private void addServerButton_Click(object sender, EventArgs e) 
{ 
    serverListBox.Items.Add(this.serverTextBox.Text); 

    string path = @"C:\\Public Key Pin\UserServerData.txt"; 
    File.AppendAllText(path, this.serverTextBox.Text+"\n"); 
} 

如果你想加載SAVEFILE的所有行:

// Add all lines to ListBox 
serverListBox.Items.AddRange(File.ReadAllLines(@"C:\\Public Key Pin\UserServerData.txt")); 

如果只想最後一行:

var lines = File.ReadAllLines(@"C:\\Public Key Pin\UserServerData.txt"); 
// Add last line to ListBox: 
if (lines.Length > 0) serverListBox.Items.Add(lines[lines.Length - 1]); 
+0

好吧,我想: –

+0

StreamReader的SR =新的StreamReader(@ 「C:\\公共鑰匙銷\ UserServerData.txt」) ; serverListBox.Items.Add = sr.ReadLine(); –

+0

你能告訴我你使用WinForms或WPF,我會爲你寫這個版本嗎? – Sakura

0

使用sw.AppendText(this.serverTextBox.Text);代替

-1

你壽LD使用:現在怎麼我從文本文件到列表框中添加項目

 string path = @"C:\\Public Key Pin\UserServerData.txt"; 
    using (StreamWriter sw = File.CreateText(path)) 
    { 
     sw.WriteLine(this.serverTextBox.Text); 
    }