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

如何读取音频文件的字符串数组类型属性?(WindowsAPICodePack)

解决ShellFile读取多值音频属性显示System.String[]的问题

SystemProperties.System.Music.Artist这类属性属于多值属性,底层存储的是string[]数组类型。直接调用ToString()会返回数组的类型名称System.String[],强制转换为string则会触发类型转换异常。

解决方法是先判断属性值的类型,若为字符串数组则拼接为可读的单个字符串:

using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;

private void GetData()
{
    string filePath = "E:\\mySong.mp3";
    var shellFile = ShellFile.FromParsingName(filePath);

    // 读取单值属性:专辑标题、专辑艺术家
    txtAlbum.Text = shellFile.Properties.GetProperty(SystemProperties.System.Music.AlbumTitle)?.ValueAsObject?.ToString() ?? string.Empty;
    txtArtist.Text = shellFile.Properties.GetProperty(SystemProperties.System.Music.AlbumArtist)?.ValueAsObject?.ToString() ?? string.Empty;

    // 读取多值属性:参与艺术家
    var artistsPropertyValue = shellFile.Properties.GetProperty(SystemProperties.System.Music.Artist)?.ValueAsObject;
    if (artistsPropertyValue is string[] artistsArray)
    {
        // 用逗号分隔拼接数组元素,可根据需求替换分隔符(如分号、换行符)
        txtArtists.Text = string.Join(", ", artistsArray);
    }
    else
    {
        // 兼容属性为单值或空的情况
        txtArtists.Text = artistsPropertyValue?.ToString() ?? string.Empty;
    }
}

补充说明

  • 常见的多值音频属性还包括Genre(流派)、Composer(作曲者)等,都可以用同样的方式处理
  • 使用?.空值运算符避免空引用异常,?? string.Empty确保属性不存在或为空时返回空字符串而非null
  • 可根据需求调整拼接分隔符,比如用Environment.NewLine实现换行显示多个艺术家

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 16:35:09