日期:2014-05-18  浏览次数:21006 次

关于listbox里数据导出的问题
将listbox里所有的数据导出到text文件里去
我的代码是这样的
  saveFileDialog1.Filter = "Text File (*.txt)|*.txt";//文件筛选器
  //p.ShowReadOnly = true;//ReadOnly复选框
  //p.Multiselect = true;//允许选择多个文件
  saveFileDialog1.Title = "sdff";//对话框标题
  if (saveFileDialog1.ShowDialog() == DialogResult.OK)
  {
  FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create);
  StreamWriter sw = new StreamWriter(fs, Encoding.Unicode);
   
  for (int i = 0; i <= this.listBox1.Items.Count; i++)
  {
  sw.Write(this.listBox1.Items[i].ToString());
  sw.Write("\r\n");
  }
  }
  saveFileDialog1.Dispose();
但是text文件里始终没数据 请哪位大侠指点指点


------解决方案--------------------
注意记得要flush,good luck

private void button1_Click(object sender, EventArgs e) {
string filepath = "";
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
if (saveFileDialog1.ShowDialog() == DialogResult.OK) {
filepath = saveFileDialog1.FileName;
StreamWriter sTmp = new StreamWriter(filepath);
sTmp.Write("你想要写入的文本 ");
sTmp.Flush();
sTmp.Close();
}
}

------解决方案--------------------
lz代码语句:“for (int i = 0; i <= this.listBox1.Items.Count; i++) ”
其中i <= this.listBox1.Items.Count;应该修正为:
i < this.listBox1.Items.Count;
还有最好加上try/catch,参考代码:

FileStream fs = null;
StreamWriter sw = null;
try
{
fs = new FileStream(@"E:\test.txt", FileMode.Create);
sw = new StreamWriter(fs, Encoding.Unicode);

for (int i = 0; i < this.listBox1.Items.Count; i++)
{
sw.WriteLine(this.listBox1.Items[i].ToString());
}
sw.Flush();
}
finally
{
sw.Close();
fs.Close();
}