namespace AIStudio.Tools.OpenXml; /// /// Writes a complete Office document into the file the user chose. /// /// /// The document comes about in a file of its own first, and only the complete document is streamed into the target. /// Nothing is created next to the target: inside the Flatpak, the save dialog grants access to exactly the chosen /// file, and to nothing next to it. A failure before the document is complete therefore leaves the target untouched. /// internal static class TargetFile { /// /// Streams a complete document into the file the user chose. /// /// /// The file is written over rather than removed and created anew, which the Flatpak would not allow. Once writing /// has begun, a failure removes the file: a half-written document is worse than none. A file which cannot even be /// opened, e.g., because PowerPoint or Word shows it, stays as it is. /// /// The complete document. /// The path of the file the user chose. It may exist; the save dialog asked about overwriting it. /// Where to report a half-written target which cannot be removed. /// The cancellation token. public static async Task WriteOverAsync(string documentPath, string targetPath, ILogger logger, CancellationToken token) { await using var document = new FileStream(documentPath, FileMode.Open, FileAccess.Read, FileShare.Read); var target = new FileStream(targetPath, FileMode.Create, FileAccess.Write, FileShare.None); try { await using (target) await document.CopyToAsync(target, token); } catch { DeleteQuietly(targetPath, logger); throw; } } /// /// Removes a file which is of no use anymore, and only reports when that fails. /// /// The file. /// Where to report a file which cannot be removed. public static void DeleteQuietly(string path, ILogger logger) { try { if (File.Exists(path)) File.Delete(path); } catch (Exception e) { logger.LogWarning(e, "The file '{FilePath}' cannot be deleted.", path); } } }