You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C#(AvaloniaUI)跨Windows和Linux获取下载文件夹

跨Windows/Linux获取下载文件夹的C#实现方案(兼容AvaloniaUI)

方法一:使用.NET内置的跨平台枚举(最简方案)

.NET Core 3.0及以上版本提供了Environment.SpecialFolder.Downloads枚举,可直接跨Windows和Linux获取标准下载文件夹路径,Avalonia完全兼容该API。

using System;
using System.IO;

public string GetDownloadsFolder()
{
    try
    {
        return Environment.GetFolderPath(Environment.SpecialFolder.Downloads);
    }
    catch (ArgumentException)
    {
        // 部分小众Linux发行版可能不支持该枚举,降级到用户目录下的默认Downloads文件夹
        var userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
        return Path.Combine(userProfile, "Downloads");
    }
}

方法二:基于Avalonia自身存储API(框架适配方案)

Avalonia的StorageProvider提供了平台无关的已知文件夹获取能力,尤其适合沙盒化环境(如Linux Flatpak包),能自动处理平台特定的权限和路径映射。

using Avalonia.Platform.Storage;
using System.IO;
using System.Threading.Tasks;

public async Task<string> GetDownloadsFolderAsync()
{
    var storageProvider = Avalonia.Application.Current?.MainWindow?.StorageProvider;
    if (storageProvider == null)
        throw new InvalidOperationException("需在UI线程调用,或传入有效窗口实例以获取StorageProvider");

    var downloadFolder = await storageProvider.TryGetFolderFromPathAsync(KnownFolder.Downloads);
    return downloadFolder?.Path.LocalPath ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");
}

方法三:手动适配系统规范(兜底方案)

若需更精准适配Linux的自定义路径规则,可读取XDG_DOWNLOAD_DIR环境变量,同时兼容Windows平台:

using System;
using System.IO;
using System.Runtime.InteropServices;

public string GetDownloadsFolderFallback()
{
    var userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
    
    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
    {
        return Environment.GetFolderPath(Environment.SpecialFolder.Downloads);
    }
    else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
    {
        // 优先读取用户自定义的XDG下载路径
        var xdgDownloadDir = Environment.GetEnvironmentVariable("XDG_DOWNLOAD_DIR");
        return string.IsNullOrEmpty(xdgDownloadDir) ? Path.Combine(userProfile, "Downloads") : xdgDownloadDir;
    }

    return userProfile;
}

方案选择建议

  • 优先使用方法一:代码简洁,依赖.NET原生能力,适配绝大多数场景;
  • Avalonia项目推荐方法二:贴合框架设计,沙盒环境下表现更稳定;
  • 方法三作为兜底,用于需要极致兼容小众系统或自定义路径的场景。

内容的提问来源于stack exchange,提问作者Nickolas Etyuhibosecyu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 21:30:04