Reading and writing to a CSV in C#

A simple way of reading and writing to a CSV is by using Visual Basic assembly file called FileIO, which can be easily imported by searching in the Reference Manager within Visual Studio Microsoft.VisualBasic.FileIO”

Write to the CSV

var destinationPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var destinationFile = Path.Combine(destinationPath, "MyContacts.csv");
private readonly string filename = destinationFile;
public void WriteToCsv(string input)
{
using (FileStream fileStream = new FileStream(filename, FileMode.Append,  FileAccess.Write))
using (var outputFile = new StreamWriter(fileStream))
{
outputFile.WriteLine(input);
}
}

Within the WriteToCsv method, we need to use filestream in a “using” block which will automatically disposed/cleans up the resource once it’s finished with it. In addition we can specifiy access rights. This is crucial, without specifying, by default the file will not save in many locations on your file system.

Within that block we can use a Streamwriter object to write line the input into our output file.

Read from the CSV

Reading from a CsV file requires the use of the TextFieldParser class. Pay attention to setting up your parser options, especially choosing your prefered delimiter. Look at docs for more options.

public void Parse_CSV(String Filename)

using (var parser = new TextFieldParser(filename))
{
parser.SetDelimiters(",");
parser.TrimWhiteSpace = true;

while (!parser.EndOfData)
{
string[] fieldRow = parser.ReadFields();
foreach (string fieldRowCell in fieldRow)
{

// do something with firelds
}

}
}

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s