Tutorial: Write a Basic CSV File with C#

This tutorial demonstrates how to use the Xilytix TFieldedText component to write headings and records to a CSV file.

The 2 headings and 4 records to be written to the file, are shown in the table below:

Pet Name Age Color Date Received Price Needs Walking Type
(Years) (Dollars)
Rover 4.5 Brown 12 Feb 2004 80 True Dog
Charlie Gold 5 Apr 2007 12.3 False Fish
Molly 2 Black 12 Dec 2006 25 False Cat
Gilly White 10 Apr 2007 10 False Guinea Pig

By using TFieldedText to write the CSV file, you do not have to worry about formatting.  TFieldedText will ensure that the data in the CSV file is laid out as specified by the Meta.

The full source code for this tutorial lesson can be downloaded from the component's home page

Step 1: Select a folder

Create or select an empty folder for the program we are going to develop.

Step 2: Create Fielded Text Meta file

The Meta file specifies the structure of the text file.  In this step we will create a Meta file called "BasicExample.ftm" for the text file.  There are 2 ways of doing this.

The easy way is to simply download the Meta file from here (Right Click | Save Link/Target As) and place in the folder where the compiled executable will run from (normally in the bin\Debug folder beneath the project folder).

Alternatively, you can create it with a Fielded Text Editor.  This will provide a better understanding of what a Meta file actually is.  Follow the steps here to create the "BasicExample.ftm" and then save it into the folder where the compiled executable will run from.

The contents of the Fielded Text Meta File should be similar to the text shown below

<?xml version="1.0" encoding="utf-8"?>
<FieldedText HeadingLineCount="2" HeadingWritePrefixSpace="True">
  <Field Name="PetName" ValueQuotedType="Always" HeadingWritePrefixSpace="False" Headings="Pet Name" />
  <Field DataType="Float" Name="Age" ValueWritePrefixSpace="True" Headings="Age, " />
  <Field Name="Color" ValueWritePrefixSpace="True" Headings="Color, (Years)" />
  <Field DataType="DateTime" Name="DateReceived" ValueWritePrefixSpace="True" Headings="Date Received, " Format="d MMM yyyy" />
  <Field DataType="Decimal" Name="Price" ValueWritePrefixSpace="True" Headings="Price, (Dollars)" />
  <Field DataType="Boolean" Name="NeedsWalking" ValueWritePrefixSpace="True" Headings="Needs Walking, " />
  <Field Name="Type" ValueQuotedType="Always" ValueWritePrefixSpace="True" Headings="Type" />
</FieldedText>

Step 3: Create a WinForm project

Create a WinForm project in your development environment.  Save it to the project folder.

Step 4: Reference the FieldedText Assembly

Add a reference to the Xilytix.FieldedText.dll and Borland.Delphi.dll assemblies.  These assemblies can be downloaded from here.

Step 5: Place controls on Form

Add the following items to a form in the project:

Step 6: Add 'using' lines

Make sure that the following 'using' lines are included in the code for the form.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Text;
using System.IO;
using Xilytix.FieldedText;

Step 7: Button Click event

Add the following code to the Click event of the button:

{
  TFieldedText FieldedText = new TFieldedText();

  // Load the Meta which describes the text file
  // A Fielded Text Editor is used to create the Meta File.
  FieldedText.LoadMeta("BasicExample.ftm");

  // Find Field Indices
  int PetNameIdx = FieldedText.IndexOfField("PetName");
  int AgeIdx = FieldedText.IndexOfField("Age");
  int ColorIdx = FieldedText.IndexOfField("Color");
  int DateReceivedIdx = FieldedText.IndexOfField("DateReceived");
  int PriceIdx = FieldedText.IndexOfField("Price");
  int NeedsWalkingIdx = FieldedText.IndexOfField("NeedsWalking");
  int TypeIdx = FieldedText.IndexOfField("Type");

  // Set up Headings
  FieldedText.GetFields(PetNameIdx).SetHeadings(0, "Pet Name");
  FieldedText.GetFields(AgeIdx).SetHeadings(0, "Age");
  FieldedText.GetFields(AgeIdx).SetHeadings(1, "(Years)");
  FieldedText.GetFields(ColorIdx).SetHeadings(0, "Color");
  FieldedText.GetFields(DateReceivedIdx).SetHeadings(0, "Date Received");
  FieldedText.GetFields(PriceIdx).SetHeadings(0, "Price");
  FieldedText.GetFields(PriceIdx).SetHeadings(1, "(Dollars)");
  FieldedText.GetFields(NeedsWalkingIdx).SetHeadings(0, "Needs Walking");
  FieldedText.GetFields(TypeIdx).SetHeadings(0, "Type");

  // Create a writer
  StringBuilder Bldr = new StringBuilder();
  StringWriter Writer = new StringWriter(Bldr);

  // Start writing.  Header will automatically be written
  FieldedText.BeginWrite(Writer);

  // Set up values for first record
  FieldedText.GetFields(PetNameIdx).AsString = "Rover";
  FieldedText.GetFields(AgeIdx).AsDouble = 4.5;
  FieldedText.GetFields(ColorIdx).AsString = "Brown";
  FieldedText.GetFields(DateReceivedIdx).AsDateTime = new DateTime(2004, 2, 12);
  FieldedText.GetFields(PriceIdx).AsDecimal = 80.0M;
  FieldedText.GetFields(NeedsWalkingIdx).AsBoolean = true;
  FieldedText.GetFields(TypeIdx).AsString = "Dog";

  // Write First Record
  FieldedText.WriteRecord();

  // Repeat for next 3 records
  FieldedText.GetFields(PetNameIdx).AsString = "Charlie";
  FieldedText.GetFields(AgeIdx).Null = true;
  FieldedText.GetFields(ColorIdx).AsString = "Gold";
  FieldedText.GetFields(DateReceivedIdx).AsDateTime = new DateTime(2007, 4, 5);
  FieldedText.GetFields(PriceIdx).AsDecimal = 12.3M;
  FieldedText.GetFields(NeedsWalkingIdx).AsBoolean = false;
  FieldedText.GetFields(TypeIdx).AsString = "Fish";
  FieldedText.WriteRecord();

  FieldedText.GetFields(PetNameIdx).AsString = "Molly";
  FieldedText.GetFields(AgeIdx).AsDouble = 2.0;
  FieldedText.GetFields(ColorIdx).AsString = "Black";
  FieldedText.GetFields(DateReceivedIdx).AsDateTime = new DateTime(2006, 12, 12);
  FieldedText.GetFields(PriceIdx).AsDecimal = 25M;
  FieldedText.GetFields(NeedsWalkingIdx).AsBoolean = false;
  FieldedText.GetFields(TypeIdx).AsString = "Cat";
  FieldedText.WriteRecord();

  FieldedText.GetFields(PetNameIdx).AsString = "Gilly";
  FieldedText.GetFields(AgeIdx).Null = true;
  FieldedText.GetFields(ColorIdx).AsString = "White";
  FieldedText.GetFields(DateReceivedIdx).AsDateTime = new DateTime(2007, 4, 10);
  FieldedText.GetFields(PriceIdx).AsDecimal = 10.0M;
  FieldedText.GetFields(NeedsWalkingIdx).AsBoolean = false;
  FieldedText.GetFields(TypeIdx).AsString = "Guinea Pig";
  FieldedText.WriteRecord();

  // Finish Writing
  FieldedText.EndWrite();
  Writer.Close();

  // Place in TextBox
  CsvTextBox.Text = Bldr.ToString();
}

Step 8: Compile and Run

Compile and run the program.  When the button is clicked, the program will do the following:

  1. Create a TFieldedText object
  2. Load the Meta
  3. Find the indices of the fields
  4. Set up the headings in the FieldedText object
  5. Create a StringWriter to write text to a StringBuilder
  6. Use FieldedText.BeginWrite to initiate writing of text.  This call will automatically write the headings.
  7. Write the records
  8. Use FieldedText.EndWrite to finish the writing process
  9. Place generated string in CsvTextBox