首先是一个令人沮丧的事实:https://www.base64decode.org/可以做我想做的事情。
我正在尝试编码和解码(往返于base64)由图像处理工具MVTec Halcon生成的模型文件(.shm),因为我想将其存储在xml文件中。
如果我打开它,它有这种奇怪的形式:
HSTF ÿÿÿÿ¿€ Q¿ÙG®záH?Üä4©±w?Eè}‰@?ð ................
我使用这种方法对它进行编码和解码:
public static string Base64Encode(string text)
{
Byte[] textBytes = Encoding.Default.GetBytes(text);
return Convert.ToBase64String(textBytes);
}
public static string Base64Decode(string base64EncodedData)
{
Byte[] base64EncodedBytes = Convert.FromBase64String(base64EncodedData);
return Encoding.Default.GetString(base64EncodedBytes);
}
并从这样的gui调用方法:
var model = File.ReadAllText(@"C:\Users\\Desktop\model_region_nut.txt");
var base64 = ImageConverter.Base64Encode(model);
File.WriteAllText(@"C:\Users\\Desktop\base64.txt", base64);
var modelneu = ImageConverter.Base64Decode(File.ReadAllText(@"C:\Users\\Desktop\base64.txt"));
File.WriteAllText(@"C:\Users\\Desktop\modelneu.txt", modelneu);
我对modelneu的结果是:
HSTF ?????? Q??G?z?H???4??w??E?}??@??
所以你可以看到有很多缺少的字符..我猜问题是由使用.Default引起的。
谢谢你的帮助,米歇尔
如果您正在使用二进制数据,则根本没有理由进行文本解码和编码。这样做只会以各种方式破坏数据,即使您使用的是一致的字符编码。
只需使用File.ReadAllBytes()
而不是File.ReadAllText()
并跳过不必要的Encoding
步骤。
问题是阅读文件与未指定的encoding
,检查this question。
正如前面提到的,你可以使用ReadAllText的重载来指定编码,并且对于写入你必须为WriteAllText指定编码我建议使用UTF-8编码,所以:
var model = File.ReadAllText(@"C:\Users\pichlerm\Desktop\model_region_nut.txt",Encoding.UTF8);
var base64 = ImageConverter.Base64Encode(model);
File.WriteAllText(@"C:\Users\\Desktop\base64.txt", base64,Encoding.UTF8);
var modelneu = ImageConverter.Base64Decode(File.ReadAllText(@"C:\Users\\Desktop\base64.txt"));
File.WriteAllText(@"C:\Users\pichlerm\Desktop\modelneu.txt", modelneu);