0

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);
        }
    }
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
B.Cox
  • 23
  • 5
  • 2
    That code does not release the handle on that file. It will essentially be locked until your app terminates. – Ross Bush May 12 '16 at 22:55

2 Answers2

3

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
}
Gusman
  • 14,905
  • 2
  • 34
  • 50
  • I used close and it worked, thanks; but I'll use AppendAllText; it's a better method I think. – B.Cox May 13 '16 at 00:42
  • Yes, if you want to append text to a file AppendAllText would be the simplest and less error-prone solution :) – Gusman May 13 '16 at 00:43
3

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

Grant Winney
  • 65,241
  • 13
  • 115
  • 165