C# 将列表框的项目保存到文本文件
如何使用C# 将列表框的项目保存到文本文件,c#,listbox,text-files,C#,Listbox,Text Files,如何使用保存文件对话框将列表框项的内容保存到文本文件 我还想向文本文件中添加其他信息,并添加一个消息框,在成功保存后显示saved。保存 // fetch the selected Text from your list string textToRight = listBox1.SelectedItem.ToString(); // Write to a file StreamWriter sr = File.CreateText(@"testfil
保存文件对话框
将列表框
项的内容保存到文本文件
我还想向文本文件中添加其他信息,并添加一个消息框,在成功保存后显示saved。保存
// 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" );
SaveFileDialog
与ShowDialog()
一起使用,向用户显示该对话框,如果成功,则使用其OpenFile()
获取您写入的(文件)流。上面有一个例子
列表框
可以通过其项目
属性访问,该属性只是列表框上项目的集合。您在列表框中有一些事情要做,请确保将它们分开,例如
- 获取列表框内容
- 附加信息
- 写入文件
请注意保存文件时,您会遇到无数异常,请查看文档并以某种方式处理它们
// 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......
}
}
}
这应该可以做到
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!");
}
还要注意的是,StreamWriter
有一种类型。您忘了关闭StreamWriter。@roller-问题解决了吗?OpenFileDialog
?或SaveFileDialog
?可能重复:
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");
}