Files
PLib/src/PLib.Desktop/Services/SystemShell.cs
T

59 lines
1.5 KiB
C#

using System.Diagnostics;
using Microsoft.Extensions.Logging;
namespace PLib.Desktop.Services;
/// <summary>Hands a file over to whatever the operating system uses to open or show it.</summary>
public interface ISystemShell
{
void OpenFile(string path);
void RevealInFileManager(string path);
}
/// <inheritdoc cref="ISystemShell"/>
public sealed class SystemShell(ILogger<SystemShell> logger) : ISystemShell
{
public void OpenFile(string path) => Start(new ProcessStartInfo(path) { UseShellExecute = true }, path);
public void RevealInFileManager(string path)
{
ProcessStartInfo startInfo;
if (OperatingSystem.IsWindows())
{
startInfo = new ProcessStartInfo("explorer.exe", $"/select,\"{path}\"");
}
else if (OperatingSystem.IsMacOS())
{
startInfo = new ProcessStartInfo("open", ["-R", path]);
}
else
{
var folder = Path.GetDirectoryName(path);
if (folder is null)
{
return;
}
startInfo = new ProcessStartInfo("xdg-open", [folder]);
}
Start(startInfo, path);
}
private void Start(ProcessStartInfo startInfo, string path)
{
try
{
using var process = Process.Start(startInfo);
}
catch (Exception ex)
{
// Nothing actionable for the user here; a missing handler is not a crash.
logger.LogWarning(ex, "Could not hand {Path} to the shell", path);
}
}
}