Visual Studio / WPF > fileIO | DataGrid > csvファイルを読み込んでDataGridに表示する | ヘッダ文字列読み込み

```txt:動作環境
Windows 7 Pro (32bit)
Microsoft Visual Studio 2017 Community
```

参考: https://stackoverflow.com/questions/20574464/csv-text-in-datagrid-wpf

## v0.1
### 準備

アプリケーション実行ファイル生成フォルダに以下のファイルを用意する。

```test.csv
Name,Race,Codename
7of9,Borg,seven
Janeway,Human,Captain
Odo,Unknown,Odo
```

関連: [Visual Studio / WPF > アプリケーションのフォルダを取得する > System.AppDomain.CurrentDomain.BaseDirectory](http://qiita.com/7of9/items/e694489beb4c54adaba5)

### code

```MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
//
using System.IO;

namespace _170611_t1030_readCsvFile
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void B_read_Click(object sender, RoutedEventArgs e)
        {
            string appPath = System.AppDomain.CurrentDomain.BaseDirectory;
            string filename = "test.csv";
            string filepath = appPath + "\\" + filename;
            if (File.Exists(filepath) == false) {
                return;
            }
            this.DataContext = PersonService.ReadFile(filepath);
        }
    }

    // Name, Race, Codename
    public class Person
    {
        public string Name { get; set; }
        public string Race { get; set; }
        public string Codename { get; set; }
    }
    public static class PersonService
    {
        public static List<Person> ReadFile(string filepath)
        {
            var lines = File.ReadAllLines(filepath);

            var data = from l in lines.Skip(1)
                       let split = l.Split(',')
                       select new Person
                       {
                           Name = split[0],
                           Race = split[1],
                           Codename = split[2]
                       };
            return data.ToList();
        }
    }
}
```

```MainWindow.xaml
<Window x:Class="_170611_t1030_readCsvFile.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:_170611_t1030_readCsvFile"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>
            <Button x:Name="B_read" Content="Read"
                    Click="B_read_Click" Height="28" Width="100"/>
            <DataGrid Height="300"
                      AutoGenerateColumns="True"
                      ItemsSource="{Binding}"/>
        </StackPanel>
    </Grid>
</Window>
```

### run

Readボタンを押した結果
![2017-06-11_11h11_33.png](https://qiita-image-store.s3.amazonaws.com/0/32870/23f2d6dc-591e-9725-e821-72ce0de6b03f.png)

### 備考

列にあわせてClassのName Race, Codenameを定義することが必要。

可変列のcsvファイルの場合は要検討。

## v0.2 > ヘッダーも読み込むように変更

DataGridのヘッダーもファイルから読み込んでみる。

### test.csv

クラスの定義(Name, Race, Codename)とファイルのヘッダを区別するため、ファイルのヘッダに"1"を付加した。

```test.csv
Name1,Race1,Codename1
7of9,Borg,seven
Janeway,Human,Captain
Odo,Unknown,Odo
```

### code

```MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
//
using System.IO;

namespace _170611_t1030_readCsvFile
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void B_read_Click(object sender, RoutedEventArgs e)
        {
            string appPath = System.AppDomain.CurrentDomain.BaseDirectory;
            string filename = "test.csv";
            string filepath = appPath + "\\" + filename;
            if (File.Exists(filepath) == false) {
                return;
            }
            this.DataContext = PersonService.ReadFile(filepath);
            PersonService.SetHeaders(filepath, dg1);
        }
    }

    // Name, Race, Codename
    public class Person
    {
        public string Name { get; set; }
        public string Race { get; set; }
        public string Codename { get; set; }
    }
    public static class PersonService
    {
        public static List<Person> ReadFile(string filepath)
        {
            var lines = File.ReadAllLines(filepath);

            var data = from l in lines.Skip(1)
                       let split = l.Split(',')
                       select new Person
                       {
                           Name = split[0],
                           Race = split[1],
                           Codename = split[2]
                       };
            return data.ToList();
        }
        public static void SetHeaders(string filepath, DataGrid dataGrid)
        {
            var lines = File.ReadAllLines(filepath);

            int idx = 0;
            foreach(var aline in lines[0].Split(','))
            {
                dataGrid.Columns[idx].Header = aline;
                idx++;
            }
        }
    }
}

```

```MainWindow.xaml
<Window x:Class="_170611_t1030_readCsvFile.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:_170611_t1030_readCsvFile"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>
            <Button x:Name="B_read" Content="Read"
                    Click="B_read_Click" Height="28" Width="100"/>
            <DataGrid Height="300" x:Name="dg1"
                      AutoGenerateColumns="True"
                      ItemsSource="{Binding}"/>
        </StackPanel>
    </Grid>
</Window>
```

![2017-06-11_11h11_33.png](https://qiita-image-store.s3.amazonaws.com/0/32870/10769401-1ac9-6f73-93f3-be110ba8db45.png)

### 関連リンク

https://stackoverflow.com/questions/28477846/change-datagrid-column-header-text