Created
November 11, 2014 06:50
-
-
Save GeirGrusom/fdf2861f11513271469a to your computer and use it in GitHub Desktop.
CsvDeserializer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CsvDeserializer<T> | |
where T : new() | |
{ | |
private readonly string separator; | |
public CsvDeserializer() | |
: this(";") | |
{ | |
} | |
public CsvDeserializer(string separator) | |
{ | |
this.separator = separator; | |
} | |
private IList<string> ReadHeaders(string line) | |
{ | |
return line.Split(new [] { separator}, StringSplitOptions.None).Select(s => s.Trim()).ToList(); | |
} | |
private T DeserializeLine(string line, IEnumerable<string> headers) | |
{ | |
// Split up the values by the separator | |
// TODO: This does not take into account escaped values. | |
var items = line.Split(new [] {separator}, StringSplitOptions.None); | |
// Create a new row | |
var result = new T(); | |
foreach(var i in headers.Select((h, i) => new { header = h, item = items[i] })) | |
{ | |
// TODO: If the split is fixed to read escaped values this can be ommitted. | |
string csvValue = i.item.Trim('"').Trim(); | |
var property = typeof (T).GetProperty(i.header); | |
if(property == null) | |
throw new MissingFieldException(typeof(T).Name, i.header); | |
object value = Convert.ChangeType(csvValue, property.PropertyType); | |
property.SetValue(result, value); | |
} | |
return result; | |
} | |
private IEnumerable<T> DeserializeTextReader(TextReader input) | |
{ | |
string headerLine = input.ReadLine(); | |
if (string.IsNullOrEmpty(headerLine)) | |
yield break; | |
var headers = ReadHeaders(headerLine); | |
string line; | |
while (null != (line = input.ReadLine())) | |
yield return DeserializeLine(line, headers); | |
} | |
public IEnumerable<T> DeserializeContents(string file) | |
{ | |
return DeserializeTextReader(new StringReader(file)); | |
} | |
public IEnumerable<T> DeserializeStream(Stream stream) | |
{ | |
using (var streamReader = new StreamReader(stream, Encoding.UTF8, true)) | |
{ | |
return DeserializeTextReader(streamReader); | |
} | |
} | |
public IEnumerable<T> DeserializeFile(string filename) | |
{ | |
using (var file = new StreamReader(filename, Encoding.UTF8, true)) | |
{ | |
return DeserializeTextReader(file); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment