代码之家  ›  专栏  ›  技术社区  ›  oopbase Jayachandran Murugesh

将列表框项目保存到文件

c#
  •  1
  • oopbase Jayachandran Murugesh  · 技术社区  · 15 年前

    private void mstri_SaveLog_Click(object sender, EventArgs e)
    {
      Stream s;
      this.sfd_Log.Filter = "Textfiles (*.txt)|*.txt";
      DialogResult d = this.sfd_Log.ShowDialog();
      if ((d == DialogResult.OK) && (this.lb_Log.Items.Count != 0))
      {
          for (int i = 0; i < this.lb_Log.Items.Count; i++)
          {
              if ((s = this.sfd_Log.OpenFile()) != null)
              {
                  StreamWriter wText = new StreamWriter(s);
                  wText.Write(this.lb_Log.Items[i]);
                  s.Close();
              } 
          }
      }
    } 
    

    创建了一个新的文本文件,但它是 . 但我不知道我的代码哪里出错了。

    谢谢你的帮助。

    3 回复  |  直到 15 年前
        1
  •  2
  •   Slider345    15 年前

    我看到两个问题导致文件为空。第一个问题是StreamWriter正在缓冲数据,并且没有将数据写入文件。对wText.Flush()的简单调用将解决此问题。

    第二个问题是,每当StreamWriter关闭并重新打开时,它都从文件的开头开始,有效地清除了在上一次迭代中写入的内容。打开和关闭StreamWriter应该发生在for循环之外。

    我会这样做:

    
    Stream s;
    this.sfd_Log.Filter = "Textfiles (.txt)|.txt";
    DialogResult d = this.sfd_Log.ShowDialog();
    if ((d == DialogResult.OK) && (this.lb_Log.Items.Count != 0))
    {
        if ((s = this.sfd_Log.OpenFile()) != null)
        {
            StreamWriter wText = new StreamWriter(s);
            for (int i = 0; i < this.lb_Log.Items.Count; i++)
            {
    wText.Write((this.lb_Log.Items[i]));
    } wText.Flush(); s.Close(); } }
        2
  •  0
  •   DaveDev    15 年前

    尝试以下操作:

      if ((d == DialogResult.OK) && (this.lb_Log.Items.Count != 0))
      {
          for (int i = 0; i < this.lb_Log.Items.Count; i++)
          {
              if ((s = this.sfd_Log.OpenFile()) != null)
              {
    
                using (StreamWriter outfile = new StreamWriter(s)
                {
                    outfile.Write(this.lb_Log.Items[i]);
                 }
    
    
              } 
          }
    
          s.Close();
      }
    
        3
  •  0
  •   RQDQ    15 年前

    如果您使用的.NET framework版本足够新,可以使用LINQ扩展方法(我相信是3.0及更高版本),您可以执行以下操作:

    if ((d == DialogResult.OK) && (this.lb_Log.Items.Count != 0))
    {
         File.WriteAllLines(d.FileName, this.lb_Log.Items.Cast<String>());
    }