2010-02-19 60 views
5

如何使用SaveFileDialog將我的listbox項目的內容保存爲文本文件?將列表框的項目保存爲文本文件

我也想添加額外的信息到文本文件中,並且還添加了一個MessageBox說已成功保存。

+0

@roller - 這個問題解決了嗎? – 2010-02-23 02:56:04

回答

0

要保存

// fetch the selected Text from your list 
    string textToRight = listBox1.SelectedItem.ToString(); 

    // Write to a file  
    StreamWriter sr = File.CreateText(@"testfile.txt");  
    sr.Write(textToRight); 
    sr.Close(); 

消息

// display Message 
    MessageBox.Show("Information Saved Successfully"); 
+0

**您忘記關閉StreamWriter **。 – SLaks 2010-02-19 00:39:41

+0

已修復,謝謝。 – 2010-02-19 00:45:26

1

一個SaveFileDialog用於與ShowDialog()展示給用戶,如果它是成功的,使用它的OpenFile()得到(文件)Stream那你寫信給。 msdn page上有一個例子。

A ListBox可以通過其Items屬性進行訪問,該屬性只是其上的項目集合。

0

你有一些事情在那裏 - 確保你把它們分開,例如,

  • 獲取列表框中的內容
  • 附加信息
  • 寫文件

請注意!有例外,而保存文件,你可以得到,看文檔和處理這些莫名其妙的無數......

// Get list box contents 
var sb = new StringBuilder(); 
foreach (var item in lstBox.Items) 
{ 
    // i am using the .ToString here, you may do more 
    sb.AppendLine(item); 
} 
string data = sb.ToString(); 

// Append Info 
data = data + ????.... 

// Write File 
void Save(string data) 
{ 
    using(SaveFileDialog saveFileDialog = new SaveFileDialog()) 
    { 
     // optional 
     saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); 

     //saveFileDialog.Filter = ???; 

     if (saveFileDialog.ShowDialog() == DialogResult.OK) 
     { 
      File.WriteAllText(saveFileDialog.Filename); 
      MessageBox.Show("ok", "all good etc"); 
     } 
     else 
     { 
     // not good...... 
     } 
    } 
} 
+0

修復你的代碼塊格式,請...;) – IAbstract 2010-02-19 00:53:50

+0

是啊 - 那真是醜陋! (完成) – 2010-02-19 00:56:46

3

這應該這樣做。

private void button1_Click(object sender, EventArgs e) 
{ 
    OpenFileDialog f = new OpenFileDialog(); 

    f.ShowDialog();     

    ListBox l = new ListBox(); 
    l.Items.Add("one"); 
    l.Items.Add("two"); 
    l.Items.Add("three"); 
    l.Items.Add("four"); 

    string textout = ""; 

    // assume the li is a string - will fail if not 
    foreach (string li in l.Items) 
    { 
     textout = textout + li + Environment.NewLine; 
    } 

    textout = "extra stuff at the top" + Environment.NewLine + textout + "extra stuff at the bottom"; 
    File.WriteAllText(f.FileName, textout); 

    MessageBox.Show("all saved!"); 
} 
+2

'OpenFileDialog'?或'SaveFileDialog'? – spajce 2013-02-03 00:10:49

3
 var saveFile = new SaveFileDialog(); 
     saveFile.Filter = "Text (*.txt)|*.txt"; 
     if (saveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
     { 
      using (var sw = new StreamWriter(saveFile.FileName, false)) 
       foreach (var item in listBox1.Items) 
        sw.Write(item.ToString() + Environment.NewLine); 
      MessageBox.Show("Success"); 
     } 

同時,記下StreamWriterEncoding一個類型。

+0

可能的重複:http://stackoverflow.com/questions/3336186/saving-listbox-items-to-file?rq=1 – 2013-06-28 05:50:50

+0

完全真棒.. – 2014-04-21 09:55:28

相關問題