Windows10-development-file-management

提供:Dev Guides
移動先:案内検索

Windows10開発-ファイル管理

どのアプリケーションでも、最も重要なことの1つはデータです。 .net 開発者であれば、分離ストレージについて知っているかもしれません。ユニバーサルWindowsプラットフォーム(UWP)アプリケーションでも同じ概念が続きます。

ファイルの場所

これらは、アプリケーションがデータにアクセスできる領域です。 アプリケーションには特定のアプリケーション専用の領域があり、他のアプリケーションにはアクセスできませんが、ファイル内にデータを保存および保存できる領域は他にもたくさんあります。

ファイルの場所

以下に、各フォルダーの簡単な説明を示します。

S.No. Folder & Description
1

App package folder

パッケージマネージャーは、アプリのすべての関連ファイルをアプリパッケージフォルダーにインストールします。アプリはこのフォルダーからのみデータを読み取ることができます。

2

Local folder

アプリケーションは、ローカルデータをローカルフォルダーに保存します。 ストレージデバイスに制限までデータを保存できます。

3

Roaming folder

アプリケーションに関連する設定とプロパティは、ローミングフォルダーに保存されます。 他のデバイスもこのフォルダーのデータにアクセスできます。 アプリケーションごとに最大100KBのサイズに制限されています。

4

Temp Folder

一時記憶域の使用。アプリケーションを再度実行したときに一時記憶域が引き続き使用できるという保証はありません。

5

Publisher Share

同じ発行元のすべてのアプリの共有ストレージ。 アプリマニフェストで宣言されています。

6

Credential Locker

パスワード資格情報オブジェクトの安全な保管に使用されます。

7

OneDrive

OneDriveは、Microsoftアカウントに付属する無料のオンラインストレージです。

8

Cloud

データをクラウドに保存します。

9

Known folders

これらのフォルダーは、マイピクチャ、ビデオ、音楽などの既知のフォルダーです。

10

Removable storage

USBストレージデバイスまたは外付けハードドライブなど

ファイル処理API

Windows 8では、ファイル処理用の新しいAPIが導入されました。 これらのAPIは、 Windows.Storage および Windows.Storage.Streams 名前空間にあります。 System.IO.IsolatedStorage 名前空間の代わりにこれらのAPIを使用できます。 これらのAPIを使用すると、Windows PhoneアプリをWindowsストアに簡単に移植でき、アプリケーションをWindowsの将来のバージョンに簡単にアップグレードできます。

ローカル、ローミング、または一時フォルダにアクセスするには、これらのAPIを呼び出す必要があります-

StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFolder roamingFolder = ApplicationData.Current.RoamingFolder;
StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;

ローカルフォルダに新しいファイルを作成するには、次のコードを使用します-

StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile textFile = await localFolder.CreateFileAsync(filename,
   CreationCollisionOption.ReplaceExisting);

新しく作成されたファイルを開き、そのファイルにコンテンツを書き込むコードは次のとおりです。

using (IRandomAccessStream textStream = await textFile.OpenAsync(FileAccessMode.ReadWrite)) {

   using (DataWriter textWriter = new DataWriter(textStream)){
      textWriter.WriteString(contents);
      await textWriter.StoreAsync();
   }

}

以下のコードに示すように、ローカルフォルダーから同じファイルを再度開くことができます。

using (IRandomAccessStream textStream = await textFile.OpenReadAsync()) {

   using (DataReader textReader = new DataReader(textStream)){
      uint textLength = (uint)textStream.Size;
      await textReader.LoadAsync(textLength);
      contents = textReader.ReadString(textLength);
   }

}

データの読み取りと書き込みがどのように機能するかを理解するために、簡単な例を見てみましょう。 以下に、さまざまなコントロールが追加されたXAMLコードを示します。

<Page
   x:Class = "UWPFileHandling.MainPage"
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local = "using:UWPFileHandling"
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
   mc:Ignorable = "d">

   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}">

      <Button x:Name = "readFile" Content = "Read Data From File"
         HorizontalAlignment = "Left" Margin = "62,518,0,0"
         VerticalAlignment = "Top" Height = "37" Width = "174"
         Click = "readFile_Click"/>

      <TextBox x:FieldModifier = "public" x:Name = "textBox"
         HorizontalAlignment = "Left" Margin = "58,145,0,0" TextWrapping = "Wrap"
         VerticalAlignment = "Top" Height = "276" Width = "245"/>.

      <Button x:Name = "writeFile" Content = "Write Data to File"
         HorizontalAlignment = "Left" Margin = "64,459,0,0"
         VerticalAlignment = "Top" Click = "writeFile_Click"/>

      <TextBlock x:Name = "textBlock" HorizontalAlignment = "Left"
         Margin = "386,149,0,0" TextWrapping = "Wrap"
         VerticalAlignment = "Top" Height = "266" Width = "250"
         Foreground = "#FF6231CD"/>

   </Grid>

</Page>

以下に、さまざまなイベントのC#実装と、テキストファイルのデータの読み取りおよび書き込み用の FileHelper クラスの実装を示します。

using System;
using System.IO;
using System.Threading.Tasks;

using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

//The Blank Page item template is documented at
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace UWPFileHandling {

  ///<summary>
     ///An empty page that can be used on its own or navigated to within a Frame.
  ///</summary>

   public partial class MainPage : Page {
      const string TEXT_FILE_NAME = "SampleTextFile.txt";

      public MainPage(){
         this.InitializeComponent();
      }

      private async void readFile_Click(object sender, RoutedEventArgs e) {
         string str = await FileHelper.ReadTextFile(TEXT_FILE_NAME);
         textBlock.Text = str;
      }

      private async void writeFile_Click(object sender, RoutedEventArgs e) {
         string textFilePath = await FileHelper.WriteTextFile(TEXT_FILE_NAME, textBox.Text);
      }

   }

   public static class FileHelper {

     //Write a text file to the app's local folder.

      public static async Task<string>
         WriteTextFile(string filename, string contents) {

         StorageFolder localFolder = ApplicationData.Current.LocalFolder;
         StorageFile textFile = await localFolder.CreateFileAsync(filename,
            CreationCollisionOption.ReplaceExisting);

         using (IRandomAccessStream textStream = await
            textFile.OpenAsync(FileAccessMode.ReadWrite)){

               using (DataWriter textWriter = new DataWriter(textStream)){
                  textWriter.WriteString(contents);
                  await textWriter.StoreAsync();
               }
         }

         return textFile.Path;
      }

     //Read the contents of a text file from the app's local folder.

      public static async Task<string> ReadTextFile(string filename) {
         string contents;
         StorageFolder localFolder = ApplicationData.Current.LocalFolder;
         StorageFile textFile = await localFolder.GetFileAsync(filename);

         using (IRandomAccessStream textStream = await textFile.OpenReadAsync()){

            using (DataReader textReader = new DataReader(textStream)){
               uint textLength = (uint)textStream.Size;
               await textReader.LoadAsync(textLength);
               contents = textReader.ReadString(textLength);
            }

         }

         return contents;
      }
   }
}

上記のコードをコンパイルして実行すると、次のウィンドウが表示されます。

ファイル管理の実行

ここで、テキストボックスに何かを書いて、*「データをファイルに書き込む」*ボタンをクリックします。 プログラムは、データをローカルフォルダーのテキストファイルに書き込みます。 *「ファイルからデータを読み取る」*ボタンをクリックすると、プログラムは同じテキストファイルからデータを読み取ります。このファイルはローカルフォルダーにあり、テキストブロックに表示されます。

ファイル管理読み取り書き込み