将带有date.time列的csv解析为C#

时间:2019-03-22 06:23:16

标签: csv datetime parsing csvhelper

嗨,我仍然是C#的新手,我使用的是Csvhelper

我试图读取列出的csv文件

Request request = new Request.Builder().method("PUT", "some your request body")
            .url(YOUR_URL)
            .build();
        OkHttpClient httpClient = new OkHttpClient();
        try
        {
            Response response = httpClient.newBuilder()
            .readTimeout(1, TimeUnit.SECONDS)
            .build()
            .newCall(request)
            .execute();
            if(response.isSuccessful())
            {
                // notification about succesful request
            }
            else
            {
                // notification about failure request
            }
        }
        catch (IOException e1)
        {
            // notification about other problems
        }

我已经这样映射了它;

SurgicalDeviceId	CreatedAt
-1	1/01/2000 0:00
-2	1/01/2000 0:00
1	19/02/2019 12:39
2	19/02/2019 12:39
3	19/02/2019 12:39

我的阅读文字是这样的

public class Instrument
    {
        //csv map
        public int SurgicalDeviceId { get; set; }
        public DateTime CreatedAt { get; set; }
    }
    public sealed class InstrumentMap : ClassMap<Instrument>
    {
        public InstrumentMap()
        {
            Map(m => m.SurgicalDeviceId);
            Map(m => m.CreatedAt);
        }
    }

我已在此代码下断点并进行了调试,因此没有错误出现,但是运行该代码不会产生任何列表,而且我不确定如何继续。

1 个答案:

答案 0 :(得分:0)

在获取记录之前,您需要注册ClassMap。您还应该让读者使用语句,以便正确处理他们的资源。

public static List<Instrument> SplitCsv(string csv)
{
   using(var textReader = new StreamReader(@"D:\CSVStuff\Jasper.csv"))
   using(var csvr = new CsvReader(textReader))
   {
      csvr.Configuration.RegisterClassMap<InstrumentMap>();

      var instrumentList = csvr.GetRecords<Instrument>().ToList();

      return instrumentList;
   }
}

您的文化信息可能会正确处理日期。在我的计算机上,它引发了错误,因此您可能需要将TypeConverterOption添加到ClassMap中。

public sealed class InstrumentMap : ClassMap<Instrument>
{
    public InstrumentMap()
    {
        Map(m => m.SurgicalDeviceId);
        Map(m => m.CreatedAt).TypeConverterOption.Format("d/MM/yyyy H:mm");
    }
}