毎度のお約束、本記事はプレビュー状態のOS、IDE、SDKを利用しております。製品版では異なる可能性があります。
本記事はWindows 10向けのユニバーサルWindowsアプリについて学んだことを残して行く記事です。
これまでの記事はカテゴリ「UWP(Win 10) Preview」を参照ください。
今回はGitHubで公開されているユニバーサルWindowsアプリのFileAccessプロジェクトで紹介されているファイル操作について。
まぁ、アプリを動かしてみれば早いのですが、読み物としてどうぞ。
以下のメニューの一つ一つを簡単に読んでみます。

ファイルを作成します。
StorageFolder storageFolder = KnownFolders.PicturesLibrary; rootPage.sampleFile = await storageFolder.CreateFileAsync(MainPage.filename, CreationCollisionOption.ReplaceExisting);
サンプルはピクチャフォルダにファイルを作成します。Windows PhoneでもちゃんとPicturesフォルダにファイルができていました。
StorageFolder parentFolder = await file.GetParentAsync();
fileはStorageFileクラス。
await FileIO.WriteTextAsync(file, userContent);
string fileContent = await FileIO.ReadTextAsync(file);
どちらもFileNotFoundExceptionのトライキャッチ。
読み込み。
IBuffer buffer = await FileIO.ReadBufferAsync(file);
using (DataReader dataReader = DataReader.FromBuffer(buffer))
{
string fileContent = dataReader.ReadString(buffer.Length);
書きこみ。
IBuffer buffer = GetBufferFromString(userContent); await FileIO.WriteBufferAsync(file, buffer);
事前にバッファーを取得しておく。
private IBuffer GetBufferFromString(String str)
{
using (InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream())
{
using (DataWriter dataWriter = new DataWriter(memoryStream))
{
dataWriter.WriteString(str);
return dataWriter.DetachBuffer();
}
}
}
書きこみ。StorageStreamTransactionって使ったことないなぁと思って調べたらWindows 8時代からあったんですね・・・。
using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync())
{
using (DataWriter dataWriter = new DataWriter(transaction.Stream))
{
dataWriter.WriteString(userContent);
transaction.Stream.Size = await dataWriter.StoreAsync(); // reset stream size to override the file
await transaction.CommitAsync();
rootPage.NotifyUser(String.Format("The following text was written to '{0}' using a stream:{1}{2}", file.Name, Environment.NewLine, userContent), NotifyType.StatusMessage);
}
}
読み込み。
using (IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read))
{
using (DataReader dataReader = new DataReader(readStream))
{
UInt64 size = readStream.Size;
if (size <= UInt32.MaxValue)
{
UInt32 numBytesLoaded = await dataReader.LoadAsync((UInt32)size);
string fileContent = dataReader.ReadString(numBytesLoaded);
rootPage.NotifyUser(String.Format("The following text was read from '{0}' using a stream:{1}{2}", file.Name, Environment.NewLine, fileContent), NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser(String.Format("File {0} is too big for LoadAsync to load in a single chunk. Files larger than 4GB need to be broken into multiple chunks to be loaded by LoadAsync.", file.Name), NotifyType.ErrorMessage);
}
}
}
StorageFileクラスを用いて色々なプロパティを取得する。
StringBuilder outputText = new StringBuilder();
outputText.AppendLine(String.Format("File name: {0}", file.Name));
outputText.AppendLine(String.Format("File type: {0}", file.FileType));
// Get basic properties
BasicProperties basicProperties = await file.GetBasicPropertiesAsync();
outputText.AppendLine(String.Format("File size: {0} bytes", basicProperties.Size));
outputText.AppendLine(String.Format("Date modified: {0}", basicProperties.DateModified));
// Get extra properties
List<string> propertiesName = new List<string>();
propertiesName.Add(dateAccessedProperty);
propertiesName.Add(fileOwnerProperty);
IDictionary<string, object> extraProperties = await file.Properties.RetrievePropertiesAsync(propertiesName);
var propValue = extraProperties[dateAccessedProperty];
if (propValue != null)
{
outputText.AppendLine(String.Format("Date accessed: {0}", propValue));
}
propValue = extraProperties[fileOwnerProperty];
if (propValue != null)
{
outputText.Append(String.Format("File owner: {0}", propValue));
}
OS全体の最近使ったファイルではなく、アプリ固有のリスト。
StorageApplicationPermissions.MostRecentlyUsedList.Add(file, file.Name, visibility); AccessListEntryView entries = StorageApplicationPermissions.MostRecentlyUsedList.Entries; StorageApplicationPermissions.FutureAccessList.Add(file, file.Name); AccessListEntryView entries = StorageApplicationPermissions.FutureAccessList.Entries;
StorageFile fileCopy = await file.CopyAsync(KnownFolders.PicturesLibrary, "sample - Copy.dat", NameCollisionOption.ReplaceExisting);
ファイルピッカーでファイルを一つ取得して、そのファイルと対象のファイルを比較する。
FileOpenPicker picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add("*");
StorageFile comparand = await picker.PickSingleFileAsync();
if (comparand != null)
{
try
{
if (file.IsEqual(comparand))
await file.DeleteAsync();
StorageFolder storageFolder = KnownFolders.PicturesLibrary;
StorageFile file = await storageFolder.TryGetItemAsync("sample.dat") as StorageFile;
画像フォルダを利用することをマニフェストファイル(Package.appxmanifest)に記述します。
<Capabilities>
<uap:Capability Name="picturesLibrary"/>
</Capabilities>
こうやって書いてみると、Win 8、8.1時代のファイル操作ということがわかります。
Please give us your valuable comment