眺めて覚える C# Xamarin Forms(13) File 操作

#Android上の任意のファイルアクセスするときにユーザーの許可が必要です。
##主なAndroidのファイルディレクトリ
|Android.OS.Environment|ディレクトリ|
|-------------------|-----------------------|
|DirectoryAlarms|PRIVATE_EXTERNAL_STORAGE/Alarms|
|DirectoryDcim|PRIVATE_EXTERNAL_STORAGE/DCIM|
|DirectoryDownloads|PRIVATE_EXTERNAL_STORAGE/Download|
|DirectoryDocuments|PRIVATE_EXTERNAL_STORAGE/Documents|
|DirectoryMovies|PRIVATE_EXTERNAL_STORAGE/Movies|
|DirectoryMusic|PRIVATE_EXTERNAL_STORAGE/Music|
|DirectoryNotifications|PRIVATE_EXTERNAL_STORAGE/Notifications|
|DirectoryPodcasts|PRIVATE_EXTERNAL_STORAGE/Podcasts|
|DirectoryRingtones|PRIVATE_EXTERNAL_STORAGE/Ringtones|
|DirectoryPictures|PRIVATE_EXTERNAL_STORAGE/Pictures|

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/210a7844-013a-b9ac-cce8-c9f559ffa9e4.png)
##許可なしでアクセスすると下記のメッセージを出し例外として扱われます。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/fe1b134b-b5a7-c50c-ca3e-d937c731417b.png)

##手順1 Xamarin formsのプロジェクトを作成します。
##手順2 andoridプロジェクトのプロパティを開きます。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/7483c5ae-0a16-c8bd-ddd0-9fe5bd447c17.png)

###手順3 ファイルアクセスするためには、android マニフェストを開いて、必要なアクセス許可を与えます。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/04b4693b-60d0-f795-9edd-e05a51b66464.png)
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/24350702-de7c-230e-211e-ca505b9c7c9c.png)
AndroidManifest.xmlにて確認します。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/993fc7b5-aac3-e579-fd6a-bb61301e4b0e.png)

##手順4 参照にMono.Abdroid.dllを追加します。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/8333a163-1188-54f5-6ce4-90a8e0e78a09.png)


###手順5MainActivity.csに許可ダイアログ要求を追加します。

```MainActivity.cs
using System;

using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Support.V4.App;
using Android.Support.V4.Content;
using Android;

namespace PCLFiles.Droid
{
    [Activity(Label = "PCLFiles", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);
　　　　　　　//追加します。
            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted)
            {
                ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.ReadExternalStorage }, 0);
            }
            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted)
            {
                ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.WriteExternalStorage }, 0);
            }


            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/2309b3c1-3702-9933-922d-2365f2903162.png)

###手順6 MainPage.xamlにスタートボタンを設定します。

```MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="PCLFiles.MainPage">

    <StackLayout>
        <!-- Place new controls here -->
        <Label Text="Welcome to Xamarin.Forms!" 
           HorizontalOptions="Center"
            />
        <Button Text="Start" Clicked="SetUp"/>
    </StackLayout>
</ContentPage>
```
##手順7 ライブラリを追加しMainPage.xaml.csにファイル読み込み部を追加します。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/0356c481-1781-92af-5776-e37f19f580f5.png)

```MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

using Android.OS;
using System.IO;
using Android.Support.V4.App;
using Android.Support.V4.Content;
using Android;
namespace PCLFiles
{
    public class Cam
    {
        public string Name { get; set; }
        public string Image { get; set; }
    }
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

        }

        private void SetUp(object s,EventArgs e)
        {
            var tmp = new DataTemplate(() =>
            {
                var grid = new Grid() { Margin = 2 };
                grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(100) });
                grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
                var name = new Label { FontSize = 16 };
                name.SetBinding(Label.TextProperty, "Name");
                var image = new Image() { HeightRequest = 200 };
                image.SetBinding(Image.SourceProperty, "Image");
                grid.Children.Add(image, 0, 0);
                grid.Children.Add(name, 1, 0);
                return new ViewCell { View = grid };
            });
            var path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim).Path + "/Camera";
            var lst = from x in Directory.GetFiles(path).Take(10) select new Cam() { Name = Path.GetFileName(x), Image = x };
            var lv = new ListView() { ItemsSource = lst, ItemTemplate = tmp };
            Content = new Xamarin.Forms.ScrollView() { Margin = 2, Orientation = ScrollOrientation.Vertical, Content = lv };
        }
    }
}

```

##手順8 実行する。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/8af2bf9d-7639-0548-eac4-1859bd2a7324.png)

##付録
###nugetで追加したライブラリ
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/a0229217-b5d3-a63d-d8ee-ee2b3e0e96ba.png)