Search code examples
c#csvstreamwritertextwriter

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

Solution

  • 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.)