Wednesday, October 21, 2015

Creating a CSV file with C#

I came across an interesting project that some of my friends are working on, which requires them to capture some data received from the serial port and to log them into a CSV file. Giving some thought about the requirements, it occurred to me that this task could be easily get done by using C# or VB.NET.

After doing some research, I found so many complicated methods of creating CSV files and appending data into them. However, I found this extremely simple way to do the same task somewhere on the StackOverflow, and decided to give it a go.

The basic idea here is to convert all the received data into strings, and to store them in a string array. After that, they could be written into the CSV file using native File  Write commands. I have designed a simple windows form with one command button in it for writing data to the CSV file.


Click me to create the CSV file!!

This code is tested on Microsoft Visual Studio 2015. It creates a CSV file on the drive D.


 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;  
 namespace WindowsFormsApplication2  
 {  
   public partial class Form1 : Form  
   {  
     public Form1()  
     {  
       InitializeComponent();  
     }  
     private void button1_Click(object sender, EventArgs e)  
     {  
       string[] lines = { "Measurement, Value",  
                 "Temperature ,32",  
                 "Humidity , 78",  
                 "Wind Speed , 12",  
                 "Sky,Clear"  
                };  
       System.IO.File.WriteAllLines(@"D:\WriteData.csv", lines);  
     }  
   }  
 }  

The resultant CSV file on my local drive D 


However, this code does not append new data to the CSV file. Instead, it overwrites the data in the CSV file at each button press. To append data, use "System.IO.File.AppendAllLines".

     private void button1_Click(object sender, EventArgs e)  
     {  
       string[] lines = { "Measurement, Value",  
                 "Temperature ,32",  
                 "Humidity , 78",  
                 "Wind Speed , 12",  
                 "Sky,Clear"  
                };  
       System.IO.File.AppendAllLines(@"D:\WriteData.csv", lines);  
     }  

By combining this code with the built in serial communication functions, one could easily get the above mentioned task done.