Wednesday, 30 January 2013

Writing Data to CSV File using C#



Step 1: Create New Project
Step 2: Add “System.IO” namespace.
Step 3: Create the form as follows.
Step 4: Write the following code.

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

namespace WritingCSV
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            string FirstName = textBoxFirstName.Text;
            string LastName = textBoxLastName.Text;
            string Age = textBoxAge.Text;
            listBoxFirstName.Items.Add(FirstName);
            listBoxLastName.Items.Add(LastName);
            listBoxAge.Items.Add(Age);
            textBoxFirstName.ResetText();
            textBoxLastName.ResetText();
            textBoxAge.ResetText();
        }

        private void buttonWrite_Click(object sender, EventArgs e)
        {
            string FilePath = textBoxFilePath.Text;
            string[] FirstNames = new string[listBoxFirstName.Items.Count];
            string[] LastNames = new string[listBoxFirstName.Items.Count];
            string[] Ages = new string[listBoxFirstName.Items.Count];
            string[] TotalData = new string[listBoxFirstName.Items.Count];
            for (int i = 0; i < listBoxFirstName.Items.Count; i++)
            {
                FirstNames[i] = listBoxFirstName.Items[i].ToString();
                LastNames[i] = listBoxLastName.Items[i].ToString();
                Ages[i] = listBoxAge.Items[i].ToString();
                TotalData[i] = FirstNames[i] + "," + LastNames[i] + "," + Ages[i];
            }
            File.WriteAllLines(FilePath, TotalData);
            MessageBox.Show("CSV File Created Successfully", "Success");
        }
    }
}

Step 5: Output




2 comments: