Files
AI-Studio/app/MindWork AI Studio/Tools/OpenXml/TargetFile.cs
T

58 lines
2.4 KiB
C#

namespace AIStudio.Tools.OpenXml;
/// <summary>
/// Writes a complete Office document into the file the user chose.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
internal static class TargetFile
{
/// <summary>
/// Streams a complete document into the file the user chose.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="documentPath">The complete document.</param>
/// <param name="targetPath">The path of the file the user chose. It may exist; the save dialog asked about overwriting it.</param>
/// <param name="logger">Where to report a half-written target which cannot be removed.</param>
/// <param name="token">The cancellation token.</param>
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;
}
}
/// <summary>
/// Removes a file which is of no use anymore, and only reports when that fails.
/// </summary>
/// <param name="path">The file.</param>
/// <param name="logger">Where to report a file which cannot be removed.</param>
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);
}
}
}