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

Base64文件读写触发System.FormatException问题求助

问题根源与解决方案

核心问题

你的写入和读取逻辑不匹配:

  • 写入时,每次向文件追加独立的Base64编码片段(对应"\n" + _especie的Base64结果)
  • 读取时,却把整个文件的所有内容当作一个完整的Base64字符串解码

多个独立Base64串直接拼接后,几乎不可能是合法的Base64格式(Base64要求总长度为4的整数倍,且字符仅包含A-Z、a-z、0-9、+、/,末尾最多两个=填充),因此触发FormatException。另外,写入时把换行符\n包含在Base64编码内,会导致解码后的数据多出不必要的换行,进一步干扰后续行读取逻辑。


解决方案一:每行存储一个独立Base64项(推荐)

这种方式更易维护,符合文本文件的行式存储习惯。

修改写入代码

不要把\n包含到Base64编码中,直接追加Base64字符串+换行符,确保每行对应一个物种的Base64编码:

string base64Item = System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(_especie));
System.IO.File.AppendAllText(
    @"C:\Users\Public\Documents\Jurassic Command Line\" + _isla + "_Dinosaurs.jcl", 
    base64Item + Environment.NewLine);

修改读取代码

按行读取文件,每行单独解码,避免把整个文件当作单一Base64串:

comboBox.Items.Clear();
string[] base64Lines = File.ReadAllLines(@"C:\Users\Public\Documents\Jurassic Command Line\Nublar_Dinosaurs.jcl");
foreach(string line in base64Lines)
{
    if(string.IsNullOrWhiteSpace(line)) continue; // 跳过空行
    string decodedItem = Decodificar(line);
    comboBox.Items.Add(decodedItem);
}

static string Decodificar(string data)
{
    byte[] encodedDataAsBytes = Convert.FromBase64String(data);
    string returnValue = Encoding.ASCII.GetString(encodedDataAsBytes);
    return returnValue;
}

解决方案二:保持单一Base64串存储

如果需要维持整个文件为一个Base64串的结构,需先解码原有内容、添加新项后重新编码,而非追加独立Base64片段。

修改写入代码

string filePath = @"C:\Users\Public\Documents\Jurassic Command Line\" + _isla + "_Dinosaurs.jcl";
string existingDecoded = string.Empty;

// 读取并解码原有内容(如果文件存在)
if(File.Exists(filePath))
{
    existingDecoded = Decodificar(File.ReadAllText(filePath));
}

// 拼接新物种(用换行分隔)
string newDecodedData = string.IsNullOrEmpty(existingDecoded) 
    ? _especie 
    : existingDecoded + "\n" + _especie;

// 重新编码为完整Base64串并写入
File.WriteAllText(filePath, Convert.ToBase64String(Encoding.ASCII.GetBytes(newDecodedData)));

读取代码可保持不变

此时整个文件是合法的单一Base64串,原读取逻辑可以正常工作。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 23:35:37