借助网络配置,控制Modbus工具的日志显示,避免卡死界面
智能大石头 authored at 2021-12-11 22:09:19
2.97 KiB
XCoder
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Platform.Storage;
using NewLife;

namespace NewLife.XCoder.Services;

/// <summary>文本记录导出:把工具页上的日志/记录保存为文本文件</summary>
public static class TextLogExporter
{
    /// <summary>用系统文件管理器定位到指定文件,失败时打开所在目录</summary>
    /// <param name="path">文件路径</param>
    /// <returns>是否成功拉起系统程序</returns>
    public static Boolean Reveal(String? path)
    {
        if (path.IsNullOrEmpty() || !File.Exists(path)) return false;

        try
        {
            if (OperatingSystem.IsWindows())
            {
                Process.Start(new ProcessStartInfo("explorer.exe", $"/select,\"{path}\"") { UseShellExecute = true });
                return true;
            }

            var dir = Path.GetDirectoryName(path!);
            return OpenPath(dir ?? path!);
        }
        catch (Exception)
        {
            return false;
        }
    }

    /// <summary>用系统默认程序打开文件或目录</summary>
    /// <param name="path">路径</param>
    /// <returns>是否成功拉起系统程序</returns>
    public static Boolean OpenPath(String? path)
    {
        if (path.IsNullOrEmpty()) return false;

        try
        {
            var fileName = OperatingSystem.IsWindows() ? "explorer.exe" : OperatingSystem.IsMacOS() ? "open" : "xdg-open";
            Process.Start(new ProcessStartInfo(fileName, $"\"{path}\"") { UseShellExecute = true });

            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

    /// <summary>弹出保存对话框并写入文本</summary>
    /// <param name="owner">用于取 TopLevel 的控件</param>
    /// <param name="title">对话框标题</param>
    /// <param name="suggestedName">建议文件名</param>
    /// <param name="content">要保存的文本</param>
    /// <returns>保存的文件名;取消或失败返回 null</returns>
    public static async Task<String?> SaveAsync(Control owner, String title, String suggestedName, String? content)
    {
        if (owner == null) return null;
        if (String.IsNullOrEmpty(content)) return null;

        var top = TopLevel.GetTopLevel(owner);
        if (top == null) return null;

        var file = await top.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
        {
            Title = title,
            SuggestedFileName = suggestedName,
            DefaultExtension = "txt",
            FileTypeChoices = [new FilePickerFileType(LocalizationService.T("Text files")) { Patterns = ["*.txt", "*.log"] }],
        });
        if (file == null) return null;

        await using var stream = await file.OpenWriteAsync();
        await using var writer = new StreamWriter(stream, new UTF8Encoding(true));
        await writer.WriteAsync(content!);

        return file.Name;
    }
}