/// <summary> /// 指定されたフォルダーへファイルを保存する /// 既存の同名ファイルが存在している場合はファイルを上書きする /// </summary> /// <param name="folder">フォルダー</param> /// <param name="fileName">拡張子を含むファイル名</param> /// <param name="stream">保存するデータのストリーム</param> /// <returns>ファイル</returns> public static async Task<StorageFile> SaveFileAsync(this IStorageFolder folder, string fileName, IRandomAccessStream stream) { var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); using (var outputStrm = await file.OpenAsync(FileAccessMode.ReadWrite)) { // 書き込むファイルからデータを読み込む var imageBuffer = new byte[stream.Size]; var ibuffer = imageBuffer.AsBuffer(); stream.Seek(0); await stream.ReadAsync(ibuffer, (uint)stream.Size, InputStreamOptions.None); // データをファイルに書き出す await outputStrm.WriteAsync(ibuffer); } return file; }
private static async Task<Stream> OpenStreamForWriteAsyncCore(this IStorageFolder rootDirectory, String relativePath, CreationCollisionOption creationCollisionOption) { Contract.Requires(rootDirectory != null); Contract.Requires(!String.IsNullOrWhiteSpace(relativePath)); Contract.Requires(creationCollisionOption == CreationCollisionOption.FailIfExists || creationCollisionOption == CreationCollisionOption.GenerateUniqueName || creationCollisionOption == CreationCollisionOption.OpenIfExists || creationCollisionOption == CreationCollisionOption.ReplaceExisting, "The specified creationCollisionOption has a value that is not a value we considered when devising the" + " policy about Append-On-OpenIfExists used in this method. Apparently a new enum value was added to the" + " CreationCollisionOption type and we need to make sure that the policy still makes sense."); Contract.Ensures(Contract.Result<Task<Stream>>() != null); Contract.EndContractBlock(); try { // Open file and set up default options for opening it: IStorageFile windowsRuntimeFile = await rootDirectory.CreateFileAsync(relativePath, creationCollisionOption) .AsTask().ConfigureAwait(continueOnCapturedContext: false); Int64 offset = 0; // If the specified creationCollisionOption was OpenIfExists, then we will try to APPEND, otherwise we will OVERWRITE: if (creationCollisionOption == CreationCollisionOption.OpenIfExists) { BasicProperties fileProperties = await windowsRuntimeFile.GetBasicPropertiesAsync() .AsTask().ConfigureAwait(continueOnCapturedContext: false); UInt64 fileSize = fileProperties.Size; Debug.Assert(fileSize <= Int64.MaxValue, ".NET streams assume that file sizes are not larger than Int64.MaxValue," + " so we are not supporting the situation where this is not the case."); offset = checked((Int64)fileSize); } // Now open a file with the correct options: Stream managedStream = await OpenStreamForWriteAsyncCore(windowsRuntimeFile, offset).ConfigureAwait(continueOnCapturedContext: false); return managedStream; } catch (Exception ex) { // From this API, managed dev expect IO exceptions for "something wrong": WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw(); return null; } }
/// <summary> /// Gets or creates a single file from the current folder by using the specified name. /// </summary> /// <param name="folder">The extended <see cref="IFolder">folder</see>.</param> /// <param name="name">The name of the file to get or create.</param> /// <returns>A <see cref="Task{T}">task</see> containing the retrieved <see cref="IFile">file</see>.</returns> public static async Task<IFile> GetOrCreateFileAsync( this IFolder folder, string name ) { Arg.NotNull( folder, nameof( folder ) ); Arg.NotNullOrEmpty( name, nameof( name ) ); Contract.Ensures( Contract.Result<Task<IFile>>() != null ); try { return await folder.GetFileAsync( name ).ConfigureAwait( false ); } catch ( IOException ) { return await folder.CreateFileAsync( name ).ConfigureAwait( false ); } }
/// <summary> /// Creates a temporary file. /// </summary> /// <param name="folder"></param> /// <param name="extension"></param> /// <returns></returns> public static async Task<StorageFile> CreateTempFileAsync(this StorageFolder folder, string extension = ".tmp") { if (folder == null) { folder = ApplicationData.Current.TemporaryFolder; } var fileName = await folder.CreateTempFileNameAsync( extension, DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss.ffffff")); var file = await folder.CreateFileAsync( fileName, CreationCollisionOption.GenerateUniqueName); return file; }
public static async Task<StorageFile> TryCreateFileAsync(this StorageFolder storageFolder, string name, CreationCollisionOption options = CreationCollisionOption.OpenIfExists) { StorageFile file = null; try { file = await storageFolder.CreateFileAsync(name, options); } catch { } return file; }