Reading and writing CSV files is something that will come up soon or later in your life as developer.
This is a small solution I've cooked up in a coupe of hours for a job interview.
public interface ICsvReaderWriter
{
List Read(string filePath, char delimiter);
void Write(string filePath, List lines, char delimiter);
}
public class CsvReaderWriter : ICsvReaderWriter
{
public List Read(string filePath, char delimiter)
{
var fileContent = new List();
using (var reader = new StreamReader(filePath, Encoding.Unicode))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (!string.IsNullOrEmpty(line))
{
fileContent.Add(line.Split(delimiter));
}
}
}
return fileContent;
}
public void Write(string filePath, List lines, char delimiter)
{
using (var writer = new StreamWriter(filePath, true, Encoding.Unicode))
{
foreach (var line in lines)
{
var data = line.Aggregate(string.Empty,
(current, column) => current +
string.Format("{0}{1}", column,delimiter))
.TrimEnd(delimiter);
writer.WriteLine(data);
}
}
}
}
This is a quick and dirty solution, I am sure there is plenty of room for improvment...let me know how you would improve it!!