简体   繁体   中英

Can't write to CSV

This is the first time I'm using csv and c#.

This is the code, its running, and creating the csv, but it doesn't write anything.

The code :

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

It does write, but you're checking without closing your program.

Streams don't flush instantly, they're cached, it depends on how many chars you wrote but of course if you call Flush() or Close() it will flush all the content.

So Close() your Stream, even better, surround the code with

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

There are methods available in the File class that will simplify what you're trying to do.

You can call AppendAllText and it'll create the file if needed, or simply add to it.

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

Now you don't need to create the TextWriter , so you can remove those couple of lines.

(If you want to stick with the TextWriter , then Gusman's answer is what you need - don't leave the stream open longer than you need it.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM