我使用c# MVC项目。我有一个客户类和客户表。我有一个插入函数,有四个参数name
, surname
, phone
, address
。我想逐行读取。txt文件,并使用","分割,并使用此插入函数,但我不知道如何创建算法。
static void AddCustomer(string Name, string Surname, string Phone, string Address)
{
using (var session = NHibernateHelper.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
var customer = new Customer
{
Name = Name,
Surname = Surname,
Phone = Phone,
Address = Address,
};
session.Save(customer);
transaction.Commit();
}
}
}
while ((line = file.ReadLine()) != null)
{
string text = file.ReadToEnd();
string[] lines = text.Split(',');
for (int i = 0; i < lines.Length; i++)
{
//HOW CAN I USER ADDCUSTOMER()
}
counter++;
}
差不多了。假设file
是StreamReader
,您可以将当前行分割为逗号,并将单独的部分传递给AddCustomer
方法:
while ((line = file.ReadLine()) != null)
{
// Split the line on comma
var lineParts = line.Split(',');
string name = lineParts[0];
string surname = lineParts[1];
string phone = lineParts[2];
string address = lineParts[3];
AddCustomer(name, surname, phone, address);
}
请注意,这根本没有错误检查(lineParts[1]
将爆炸,如果没有逗号在给定的行),这是一个糟糕的方式来解析CSV(如果数据包含逗号,地址往往会这样做,它将无法正常工作)。使用CSV解析库。
请参阅在c#中解析CSV文件,其中包含头文件和许多关于CSV的其他问题,建议您使用FileHelpers库。映射到CSV文件和从CSV文件映射的类将如下所示:
[DelimitedRecord(",")]
[IgnoreEmptyLines()]
public class MyProduct
{
[FieldOrder(0)]
public string Name { get; set; }
[FieldOrder(1)]
public string Surname { get; set; }
[FieldOrder(2)]
public string Phone { get; set; }
[FieldOrder(3)]
public string Address { get; set; }
}
和读取文件的代码:
var engine = new FileHelperEngine<CustomerCsvRecord>();
CustomerCsvRecord[] customers = engine.ReadFile(fileName);
foreach (var customer in customers)
{
AddCustomer(customer.Name, customer.Surname, customer.Phone, customer.Address);
}
这就够了。
string fileContent = System.IO.File.ReadAllText("YOUR_FILE_PATH");
//assumeing each customer record will be on separate line
string[] lines = fileContent.Split(new string [] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
//assuming a single line content will be like this "name,surname,phone,address"
string[] items = line.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
Customer cust = new Customer();
cust.Name = items[0];
cust.Surname = items[1];
cust.Phone = items[2];
cust.Address = items[3];
//now use this 'cust' object
}