50 lines
2.4 KiB
C#
50 lines
2.4 KiB
C#
using Duempelkas.App.Services.Models;
|
|
using System.Diagnostics;
|
|
using System.Runtime.InteropServices;
|
|
using Duempelkas.App.Services;
|
|
|
|
namespace Duempelkas.Infrastructure.Services;
|
|
|
|
public class FileSaveService(IFileDialogService dialogs) : IFileSaveService
|
|
{
|
|
public async Task<FileOperationResult> SaveFileAsync(byte[] content, string suggestedFileName)
|
|
{
|
|
string? staged = null;
|
|
try
|
|
{
|
|
var path = await dialogs.SaveAsync(suggestedFileName);
|
|
if (string.IsNullOrWhiteSpace(path)) return FileOperationResult.Cancelled();
|
|
staged = path + $".{Guid.NewGuid():N}.tmp";
|
|
await File.WriteAllBytesAsync(staged, content);
|
|
File.Move(staged, path, overwrite: true);
|
|
return new(FileOperationStatus.Success, "Datei gespeichert.", path);
|
|
}
|
|
catch (Exception ex) { return FileOperationResult.Error(ex); }
|
|
finally { try { if (staged != null && File.Exists(staged)) File.Delete(staged); } catch { } }
|
|
}
|
|
|
|
public Task<FileOperationResult> OpenFileAsync(string filePath) => OpenAsync(filePath, false);
|
|
public Task<FileOperationResult> OpenFolderAsync(string filePath) => OpenAsync(filePath, true);
|
|
|
|
private static Task<FileOperationResult> OpenAsync(string filePath, bool folder) => Task.Run(() =>
|
|
{
|
|
try
|
|
{
|
|
var path = folder ? Path.GetDirectoryName(Path.GetFullPath(filePath))! : filePath;
|
|
if (folder ? !Directory.Exists(path) : !File.Exists(path))
|
|
throw new FileNotFoundException("Der gespeicherte Pfad ist nicht mehr vorhanden.");
|
|
var start = new ProcessStartInfo { UseShellExecute = true };
|
|
if (OperatingSystem.IsWindows()) start.FileName = path;
|
|
else { start.FileName = OperatingSystem.IsMacOS() ? "open" : "xdg-open"; start.ArgumentList.Add(path); }
|
|
using var process = Process.Start(start) ?? throw new IOException("Kein Programm zum Öffnen gefunden.");
|
|
return new FileOperationResult(FileOperationStatus.Success, folder ? "Ordner geöffnet." : "Datei geöffnet.");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return new FileOperationResult(FileOperationStatus.Error,
|
|
"Der Pfad konnte nicht geöffnet werden. Die gespeicherte Datei bleibt erhalten; bitte den Speicherort im Datei-Explorer öffnen.", filePath, ex.Message);
|
|
}
|
|
});
|
|
|
|
}
|