Ich versuche, eine CSV-Datei zu speichern, die folgenden Daten in einer Liste enthalten:Eingabezeichenfolge für das Parsen von CSV nicht in der richtigen Format Datei
Ich habe den folgenden Code, der erfolgreich die CSV App_Data spart Ordner:
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;
}
jedoch die LINQ-Abfrage, eine Liste zu erhalten gibt die folgende Fehlermeldung:
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
Wenn ich in Visual Studio debuggen, kann ich nicht sehen, was in den Variablen innerhalb der LINQ-Abfrage ist, aber ich kann sehen, was in CSVProducts ist und die Eigenschaft 'Current' für es hat den Wert Null.
Dies ist die Klasse für die Produkt- und Kategorie:
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; }
}
Und was ist der Wert von 'Spalten [0]', wenn der Fehler auftritt? – David
Es sieht aus wie 'Spalten [0]' ist die ProductID? – IAbstract
Dies ist im Grunde ein Parsing-Problem. Gemäß Ihrem Code werden zwei Spalten analysiert, die 0 und 4 sind. Überprüfen Sie diese Werte. Es gibt einige nicht numerische Zeichen. – Kalyan