0
0

More than 1 year has passed since last update.

CSVを読み込もう

Last updated at Posted at 2022-06-28

CSVファイルを読み込んでデータ化してほしいんだよね。

前回、前々回とCSVファイルを読み解いた私には何も怖いものはない!
CSVを読み込もう
[続] CSVを読み込もう
かかってこいやー!!

と意気込んで、もらったCSVをエディタで開いてみると
image.png

な・ん・で・す・か?こ・れ?

先頭行に無数のNULL文字が付与されているのね。
なのでこんな感じで実装しました。

public DataTable ToDataTable()
{
    try
    {
        var dataTable = new DataTable();

        // なんか知らんけどもNULLが含まれているのでそれを良しなにする
        var fileContents = new System.IO.StreamReader(TargetPath, encoding).ReadToEnd().Replace("\0", "");

        using (var stream = new System.IO.MemoryStream(encoding.GetBytes(fileContents)))
        using (var reader = new System.IO.StreamReader(stream, encoding))
        using (var csv = new CsvHelper.CsvReader(reader, System.Globalization.CultureInfo.InvariantCulture))
        using (var dr = new CsvHelper.CsvDataReader(csv))
            dataTable.Load(dr);
        return dataTable;
    }
    catch
    {
        return null;
    }
}

CSVファイルってこんなに処理するのって難しかったっけ・・・・?

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0