将列表框中的项目保存到文本文件

6

如何使用 SaveFileDialoglistbox 中的内容保存到文本文件中?

我还想在文本文件中添加其他信息,并在成功保存后添加一个显示“已保存”的 MessageBox


@roller - 这个问题解决了吗? - Paul Kohler
5个回答

4
        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");
        }

请注意,StreamWriter的类型为编码(Encoding)


可能是重复问题:http://stackoverflow.com/questions/3336186/saving-listbox-items-to-file?rq=1 - mas_oz2k1

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
打开文件对话框?还是保存文件对话框? - spajce

1

使用 ShowDialog()SaveFileDialog向用户显示它,如果成功,使用其OpenFile()获取要写入的(文件)Stream。在msdn page上有一个示例。

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

保存

   // 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" ); 

你忘记关闭你的StreamWriter了。 - SLaks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接