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

云文件API中如何解析StorageFile自定义状态的byte[]数据?

解决StorageProviderCustomStates字节数组反序列化问题

System.StorageProviderCustomStates返回的byte[]是序列化后的StorageProviderItemProperty集合,它采用Windows Runtime专属的二进制序列化格式,无法通过常规.NET序列化或编码转换直接解析。

正确解析方法

需要借助Windows Runtime的DataReader及相关流API来解析字节数组,具体步骤如下:

  1. 将byte[]包装进InMemoryRandomAccessStream
  2. 用DataReader读取流,按固定结构逐个解析StorageProviderItemProperty字段

示例代码:

using Windows.Storage;
using Windows.Storage.Provider;
using Windows.Storage.Streams;
using Windows.Foundation.Collections;

// 假设已获取到properties字典
if (properties.TryGetValue("System.StorageProviderCustomStates", out var rawData) && rawData is byte[] bytes)
{
    using var stream = new InMemoryRandomAccessStream();
    await stream.WriteAsync(bytes.AsBuffer());
    stream.Seek(0);

    using var reader = DataReader.FromStream(stream);
    await reader.LoadAsync((uint)stream.Size);

    // 读取属性总数
    uint propertyCount = reader.ReadUInt32();
    var customProperties = new List<StorageProviderItemProperty>();

    for (uint i = 0; i < propertyCount; i++)
    {
        // 依次读取各字段:ID、显示名称、图标资源ID、属性值、可见性
        string id = reader.ReadString(reader.ReadUInt32());
        string displayName = reader.ReadString(reader.ReadUInt32());
        string iconResourceId = reader.ReadString(reader.ReadUInt32());
        string value = reader.ReadString(reader.ReadUInt32());
        bool isVisible = reader.ReadBoolean();

        customProperties.Add(new StorageProviderItemProperty
        {
            Id = id,
            DisplayName = displayName,
            IconResourceId = iconResourceId,
            Value = value,
            IsVisible = isVisible
        });
    }

    // customProperties即为你设置的自定义属性集合
}

更简便的替代方案

如果处于云文件提供程序上下文,可直接调用官方API获取属性,无需手动解析字节数组:

var properties = await StorageProviderItemProperties.GetAsync(file);
// properties是IEnumerable<StorageProviderItemProperty>类型,可直接使用

注意事项

  • System.StorageProviderCustomStates的二进制结构基于StorageProviderItemProperty的字段顺序,在WinRT版本中保持稳定
  • 需确保应用拥有访问该属性的足够权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 15:42:08