gpt4 book ai didi

c# - Net Core错误检查文件解析器缺少文本

转载 作者:行者123 更新时间:2023-12-03 08:46:34 25 4
gpt4 key购买 nike

我使用这种方法编写了一个文件解析器。

示范文本:

1,Joe,CA,58,2
2,Matt,TX,63,5

--
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace ParseTest
{
public class Customer
{

public class CustomerData
{
// These are the column names in PlatypusN.csv:
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public string CustomerState { get; set; }
public int ProductId { get; set; }
public int QuantityBought { get; set; }
}

public List<CustomerData> GetCustomer(string filename)
{
List<CustomerData> customerdata = new List<CustomerData>();
string CustomerBase = filename;
String fileToLoad = String.Format(CustomerBase);

using (StreamReader r = new StreamReader(fileToLoad))
{
string line;
while ((line = r.ReadLine()) != null)
{
string[] parts = line.Split(',');
// Skip the column names row
if (parts[0] == "id") continue;
CustomerData dbp = new CustomerData();
dbp.CustomerId = Convert.ToInt32(parts[0]);
dbp.CustomerName = parts[1];
dbp.CustomerState = parts[2];
dbp.ProductId = Convert.ToInt32(parts[3]);
dbp.QuantityBought = Convert.ToInt32(parts[4]);
customerdata.Add(dbp);
}
}
return customerdata;
}
}
}

主要测试方法:
    static void Main()
{
Customer customer = new Customer();
string filename = @"C:\Users\Desktop\Parsefile\sample.txt";

var test = customer.GetCustomer(filename);
Console.ReadKey();
}

现在,如果示例文件在一行中包含较少的数据,情况将发生什么

示范文本:
1,Joe,CA,58   // missing one number
2,Matt,TX,63,5

错误如下:
System.IndexOutOfRangeException:'索引位于数组的边界之外。'
dbp.QuantityBought = Convert.ToInt32(parts[4]);

什么是解决此问题的最干净的方法,我不想利用这样的低效率代码?
if (parts.Length - 1 >= 1)
dbp.CustomerName = parts[1];
.....
if (parts.Length - 1 >= 4)
dbp.QuantityBought = Convert.ToInt32(parts[4]);

最佳答案

只需捕获异常即可忽略该行并继续解析:

while ((line = r.ReadLine()) != null)
{
try
{
string[] parts = line.Split(',');
// Skip the column names row
if (parts[0] == "id") continue;

CustomerModel dbp = new CustomerModel
{
CustomerId = Convert.ToInt32(parts[0]),
CustomerName = parts[1],
CustomerState = parts[2],
ProductId = Convert.ToInt32(parts[3]),
QuantityBought = Convert.ToInt32(parts[4])
};

allFileCustomerData.Add(dbp);
}
catch (FormatException ex)
{

}
catch (Exception ex)
{
throw;
}
}

关于c# - Net Core错误检查文件解析器缺少文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52454117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com