【问题标题】:Can't write to CSV无法写入 CSV
【发布时间】:2016-05-12 22:51:07
【问题描述】:

这是我第一次使用 csv 和 c#。

这是代码,它正在运行,并创建 csv,但它没有写任何东西。

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace csv
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        TextWriter sw = new StreamWriter("C:\\Data.csv");
        string Var1 = "5";
        string Var2 = "325,22";
        private void button1_Click(object sender, EventArgs e)
        {
            sw.WriteLine("{0}","{2}", Var1,Var2);
        }
    }

【问题讨论】:

  • 该代码不会释放该文件的句柄。在您的应用终止之前,它基本上会被锁定。

标签: c# csv streamwriter textwriter


【解决方案1】:

File class 中有一些方法可以简化您尝试做的事情。

您可以致电AppendAllText,它会在需要时创建文件,或者直接添加。

File.AppendAllText(@"C:\Data.csv", string.Format("{0}{1}\r\n", Var1, Var2));

现在您不需要创建TextWriter,因此您可以删除这几行。

(如果您想坚持使用 TextWriter,那么 Gusman 的答案就是您所需要的 - 不要让流打开的时间超过您的需要。)

【讨论】:

  • 刚刚学到了一个新想法,谢谢。
【解决方案2】:

它确实写了,但是你在没有关闭你的程序的情况下进行检查。

流不会立即刷新,它们会被缓存,这取决于您写入的字符数,但当然,如果您调用 Flush() 或 Close(),它会刷新所有内容。

所以 Close() 你的 Stream,更好的是,用

包围代码
using (var sw = new StreamWriter("C:\\Data.csv"))
{
    //your code
}

【讨论】:

  • 我使用了 close 并且成功了,谢谢;但我会使用 AppendAllText;我认为这是一种更好的方法。
  • 是的,如果您想将文本附加到文件中,AppendAllText 将是最简单且不易出错的解决方案 :)
猜你喜欢
  • 2018-05-30
  • 1970-01-01
  • 2014-08-21
  • 1970-01-01
  • 1970-01-01
  • 2018-03-26
  • 1970-01-01
  • 2012-05-28
  • 2013-11-25
相关资源
最近更新 更多