LINQ to CSV library
Read<T>(string fileName) Read<T>(string fileName, CsvFileDescription fileDescription) Read<T>(StreamReader stream) Read<T>(StreamReader stream, CsvFileDescription fileDescription)
[CsvColumn(Name = "LastName", FieldIndex = 1)]
public String LastName { get; set; }
[CsvColumn(Name = "Sex", FieldIndex = 2)]
public String Sex { get; set; }
[CsvColumn(Name = "Birthday", FieldIndex = 3)]
public String Birthday { get; set; }
public String Memo { get; set; }
public override string ToString()
{
return string.Join(",", new string[] { FirstName, LastName, Sex, Birthday, Memo });
}
}</pre>
CsvContext cc = new CsvContext();
Person[] persons = new Person[]
{
new Person() { FirstName = "Larry", LastName = "Nung", Sex = "Boy", Birthday = "1980/04/19" }
};
cc.Write(persons, FILE_NAME);</pre>
namespace ConsoleApplication1 { public class Person { [CsvColumn (Name=“FirstName”,FieldIndex =0)] public String FirstName { get; set; }
[CsvColumn(Name = "LastName", FieldIndex = 1)]
public String LastName { get; set; }
[CsvColumn(Name = "Sex", FieldIndex = 2)]
public String Sex { get; set; }
[CsvColumn(Name = "Birthday", FieldIndex = 3)]
public String Birthday { get; set; }
public String Memo { get; set; }
public override string ToString()
{
return string.Join(",", new string[] { FirstName, LastName, Sex, Birthday, Memo });
}
}
}
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { const string FILE_NAME = “Persons.CSV”;
CsvContext cc = new CsvContext();
Person[] persons = new Person[]
{
new Person() { FirstName = "Larry", LastName = "Nung", Sex = "Boy", Birthday = "1980/04/19" }
};
cc.Write(persons, FILE_NAME);
Console.WriteLine("CSV File Content...");
Console.WriteLine(System.IO.File.ReadAllText(FILE_NAME));
Console.WriteLine("Read From CSV...");
Console.WriteLine(cc.Read<Person>(FILE_NAME).FirstOrDefault().ToString());
Console.WriteLine(new string('=', 50));
CsvFileDescription cfd = new CsvFileDescription()
{
SeparatorChar = ' ',
FirstLineHasColumnNames = true,
EnforceCsvColumnAttribute =true
};
cc.Write(persons, FILE_NAME,cfd);
Console.WriteLine("CSV File Content...");
Console.WriteLine(System.IO.File.ReadAllText(FILE_NAME));
cfd = new CsvFileDescription()
{
SeparatorChar = ' ',
FirstLineHasColumnNames = false ,
EnforceCsvColumnAttribute = true
};
Console.WriteLine("Read From CSV...");
Console.WriteLine(cc.Read<Person>(FILE_NAME, cfd).FirstOrDefault().ToString());
Console.WriteLine(new string('=', 50));
cfd = new CsvFileDescription()
{
FirstLineHasColumnNames = false,
EnforceCsvColumnAttribute = true
};
cc.Write(persons, FILE_NAME, cfd);
Console.WriteLine("CSV File Content...");
Console.WriteLine(System.IO.File.ReadAllText(FILE_NAME));
cfd = new CsvFileDescription()
{
SeparatorChar = ' ',
FirstLineHasColumnNames = false,
EnforceCsvColumnAttribute = true
};
Console.WriteLine("Read From CSV...");
Console.WriteLine(cc.Read<Person>(FILE_NAME, cfd).FirstOrDefault().ToString());
}
}
}