I have a model that contains some pretty generic properties:
public class ProductItem
{
public int ID { get; set; }
public string Description { get; set; }
public char Item { get; set; }
public decimal Price { get; set; }
public string ImagePath { get; set; }
public string Barcode { get; set; }
}
I have instances of this model populated from a CSV file using the following:
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(System.Int32));
dt.Columns.Add("Description", typeof(System.String));
dt.Columns.Add("Item", typeof(System.Char));
dt.Columns.Add("Price", typeof(System.Decimal));
dt.Columns.Add("ImagePath", typeof(System.String));
dt.Columns.Add("Barcode", typeof(System.String));
String[] csv = File.ReadAllLines(csvPath);
foreach (string csvrow in csv)
{
var fields = csvrow.Split(',');
var row = dt.NewRow();
row.ItemArray = fields;
dt.Rows.Add(row);
}
return dt;
This returns a Datatable that is then used in the following function to get the list:
private List<ProductItem> GetAllProductsCSV()
{
var filePath = Server.MapPath(@"~/CSV/products.csv");
var products = new ProductsCSV();
DataTable results = products.GetProductsFromCSV(filePath);
List<ProductItem> productItems = (from DataRow dr in results.Rows
select new ProductItem()
{
ID = Convert.ToInt32(dr["ID"]),
Description = dr["Description"].ToString(),
Item = Convert.ToChar(dr["Item"]),
Price = Convert.ToDecimal(dr["Price"]),
ImagePath = dr["ImagePath"].ToString(),
Barcode = dr["Barcode"].ToString(),
}).ToList();
return productItems;
}
Firstly, this is all starting to seem a little convoluted for something I think should be a lot easier... Am I making a lot more work for myself than I need to here?
Secondly, I am having a bit of trouble reversing this process when I make changes to a model instance and need to write it back to the CSV file. I understand that I need to re-write the whole lot back in (as I have read that you cant just update 1 row in a CSV)... But if anyone has some examples of how best to achieve this would be greatly appreciated.