1
我想存儲包含以下數據列表的CSV文件:輸入字符串解析CSV不是文件格式正確
我有下面的代碼,成功保存CSV文件中的App_Data文件夾:
public static IEnumerable<Product> CSVProducts;
public static IEnumerable<Product> CSVToList(HttpPostedFileBase CSVFile)
{
if (CSVFile == null || CSVFile.ContentLength == 0)
{
throw new InvalidOperationException("No file has been selected for upload or the file is empty.");
}
// saves the file into a directory in the App_Data folder
var fileName = Path.GetFileName(CSVFile.FileName);
var path = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/"), fileName);
CSVFile.SaveAs(path);
CSVProducts = from line in File.ReadAllLines(path).Skip(1)
let columns = line.Split(',')
select new Product
{
Id = int.Parse(columns[0]),
Barcode = columns[13],
Name = columns[1],
CategoryName = columns[9],
Description = columns[2],
Price = int.Parse(columns[4])
};
return CSVProducts;
}
然而,LINQ查詢獲取列表提供了以下錯誤信息:
Input string was not in a correct format.
Source Error:
Line 31: CSVProducts = from line in File.ReadAllLines(path).Skip(1)
Line 32: let columns = line.Split(',')
Line 33: select new Product
Line 34: {
Line 35: Id = int.Parse(columns[0]),
Source File: C:\Users\Documents\Visual Studio 2015\Projects\Website\Models\Repository.cs
Line: 33
當我在Visual Studio中進行調試時,我無法看到LINQ查詢中的變量內部有什麼,但是我可以看到CSVProducts內部的內容以及「Current」屬性的值爲null。
這是產品和類別的類:
public class Product
{
public int Id { get; set; }
public string Barcode { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
[Required]
public Byte[] Image { get; set; }
[Required]
public Decimal Price { get; set; }
[Required]
public bool ShowOnIndex { get; set; }
}
public class Category
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public Byte[] Image { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
錯誤發生時'columns [0]'的值是什麼? – David
它看起來像'columns [0]'是ProductID? – IAbstract
這基本上是一個解析問題。根據你的代碼,你正在解析兩列,這是0和4.請檢查這些值。它有一些非數字字符。 – Kalyan