XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFENewsApplication

【WinUI】新闻软件

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Runtime.InteropServices;
using System.Runtime.Versioning;

namespace XFENewsApplication.Core.Utilities.Helpers;

public static class FileHelper
{
    public static string[] RootPath { get; set; } = [@"C:\", @"D:\", @"E:\", @"F:\", @"G:\", @"H:\", @"I:\", @"J:\", @"K:\", @"L:\", @"M:\", @"N:\", @"O:\", @"P:\", @"Q:\", @"R:\", @"S:\", @"T:\", @"U:\", @"V:\", @"W:\", @"X:\", @"Y:\", @"Z:\",];
    public static long GetDirectorySize(DirectoryInfo directoryInfo)
    {
        if (!directoryInfo.Exists)
            return 0;
        long size = 0;
        FileInfo[] files = directoryInfo.GetFiles();
        foreach (FileInfo file in files)
        {
            size += file.Length;
        }
        DirectoryInfo[] directories = directoryInfo.GetDirectories();
        foreach (DirectoryInfo directory in directories)
        {
            size += GetDirectorySize(directory);
        }
        return size;
    }

    public static bool IsRootPath(string path) => RootPath.Any(rootPath => rootPath == path);

    [SupportedOSPlatform("windows")]
    public static void CreateShortCut(string targetPath, string originalPath, string argument, string description = "快捷方式")
    {
        var shellType = Type.GetTypeFromProgID("WScript.Shell")
            ?? throw new PlatformNotSupportedException("Windows Script Host is unavailable.");
        object shell = Activator.CreateInstance(shellType)
            ?? throw new InvalidOperationException("Unable to create Windows Script Host.");
        object? shortcut = null;
        try
        {
            shortcut = ((dynamic)shell).CreateShortcut(targetPath);
            dynamic wshShortcut = shortcut;
            wshShortcut.TargetPath = originalPath;
            wshShortcut.WorkingDirectory = Path.GetDirectoryName(originalPath);
            wshShortcut.WindowStyle = 1;
            wshShortcut.Description = description;
            wshShortcut.Arguments = argument;
            wshShortcut.Save();
        }
        finally
        {
            if (shortcut is not null)
                Marshal.FinalReleaseComObject(shortcut);
            Marshal.FinalReleaseComObject(shell);
        }
    }
}