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

.NETPortable v4.5中程序集资源流无法写入问题求助

问题根源与解决方案

你遇到的问题本质是嵌入资源本身是只读的——通过GetManifestResourceStream获取的流来自编译进程序集的嵌入资源,这类资源在运行时只能读取,无法直接写入,所以stream.CanWrite会返回false。

针对.NET Portable v4.5的限制(无法安装System.IO.FileSystem),你可以按照以下步骤实现修改后的数据持久化:

步骤1:读取嵌入资源的初始内容

先把嵌入资源里的JSON内容读取到内存中,方便后续修改:

var assembly = IntrospectionExtensions.GetTypeInfo(typeof(Login)).Assembly;
string initialContent;

using (Stream stream = assembly.GetManifestResourceStream("BSoft.Resources.LoggedHistory.json"))
using (StreamReader reader = new StreamReader(stream))
{
    initialContent = reader.ReadToEnd();
    // 这里可以反序列化JSON为对象,修改数据后再序列化为字符串
}

步骤2:选择可写的存储路径

.NET Portable中可以通过Environment.GetFolderPath获取系统提供的可写目录,比如本地应用数据目录,这个路径在不同平台上都会被映射到合法的可写位置:

string writablePath = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
    "LoggedHistory.json"
);

步骤3:写入修改后的内容

将修改后的JSON内容写入刚才指定的可写路径:

// 假设modifiedContent是你修改后的JSON字符串
using (StreamWriter writer = new StreamWriter(writablePath))
{
    writer.Write(modifiedContent);
}

补充:后续读取逻辑优化

之后每次需要读取数据时,优先从可写路径读取(如果存在的话),不存在再回退到嵌入资源的初始内容,这样就能保留用户修改后的状态:

string currentContent;
string writablePath = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
    "LoggedHistory.json"
);

if (File.Exists(writablePath))
{
    using (StreamReader reader = new StreamReader(writablePath))
    {
        currentContent = reader.ReadToEnd();
    }
}
else
{
    // 读取嵌入资源的初始内容
    var assembly = IntrospectionExtensions.GetTypeInfo(typeof(Login)).Assembly;
    using (Stream stream = assembly.GetManifestResourceStream("BSoft.Resources.LoggedHistory.json"))
    using (StreamReader reader = new StreamReader(stream))
    {
        currentContent = reader.ReadToEnd();
    }
}

总结一下:嵌入资源是编译到程序集里的只读资源,无法直接修改,必须复制到可写的本地存储路径后再进行写入操作,这是.NET平台的通用设计,也完全适配你的.NET Portable v4.5环境。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:14:12