Environment.GetFolderPath()不支持哪些平台?

时间:2018-08-20 16:32:21

标签: c#

根据documentation,对System.Environment.GetFolderPath的调用可能因PlatformNotSupportedException而失败:

try
{
    var appData = System.Environment.SpecialFolder.ApplicationData;
    var folder = System.Environment.GetFolderPath(appData);
    // Read/write files in ApplicationData
}
catch (System.PlatformNotSupportedException ex)
{
    System.Console.WriteLine("Environment paths not supported: " + ex.Message);
    // Does this ever actually happen?
}

不幸的是,官方文档没有列出受支持或不受支持的平台。

.net core sources中进行搜索将显示对Windows.Storage调用的引用(例如UserDataPaths.GetDefault()AppDataPaths.GetDefault()ApplicationData.RoamingFolder属性),System.Runtime.InteropServices调用和{{ 1}}电话。这些都没有标记为抛出Interop.Shell32.KnownFolders

是否存在任何实际可以触发此异常的已知平台?如果是这样,哪个?

1 个答案:

答案 0 :(得分:0)

关于System.Environment.SpecialFolderthe official document说:

  

特殊文件夹由系统默认设置,或者由   用户,安装 Windows 版本时。

不同的系统可以支持不同的KNOWN folders,或退休文件夹,更改现有文件夹的规则,等等。您也可以针对您的项目extend known folders

以下是不同操作系统的输出列表:

  1. Environment.GetFolderPath(...CommonApplicationData) is still returning "C:\Documents and Settings\" on Vista
  2. https://jimrich.sk/environment-specialfolder-on-windows-linux-and-os-x/
  3. https://johnkoerner.com/csharp/special-folder-values-on-windows-versus-mac/

通过上述链接,例如,当您调用:System.Environment.SpecialFolder.HistorySystem.Environment.SpecialFolder.Cookies或Mac / Linux中的许多其他文件夹时,它不会为您提供路径。

您可以尝试使用此方法添加简单的支持:

Environment.SpecialFolder.Cookies.Path();

这是示例代码:

public static class KnownFoldersExtensions
{
    public static string Path(this Environment.SpecialFolder folder)
    {
        var path = Environment.GetFolderPath(folder);
        if (string.IsNullOrEmpty(path))
        {
            throw new PlatformNotSupportedException();
        }
        return path;
    }
}

public static class KnownFoldersExtensions
{
    public static string Path(this Environment.SpecialFolder folder)
    {

        var path = Environment.GetFolderPath(folder);
        if (!string.IsNullOrEmpty(path))
        {
            return path;
        }

        switch (folder)
        {
            case Environment.SpecialFolder.Cookies:
                {
                    //detect current OS and give correct folder, here is for example only
                    var defaultRoot = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                    return System.IO.Path.Combine(defaultRoot, "Cookies");
                }
            //case OTHERS:
            //    {
            //        // TO DO
            //    }
            default:
                {
                    //do something or throw or return null
                    throw new PlatformNotSupportedException(folder.ToString());
                    //return null;
                }
        }

    }
}