利用C#改写JAVA中的Base64.DecodeBase64以及Inflater解码
最近正在进行项目服务的移植工作,即将JAVA服务的程序移植到DotNet平台中。
在JAVA程序中,有个HTTP请求数据头中,包含一个BASE64编码的字符串,例如:
eJyVjMENgDAMA1fpBMjnIkp3ZzZEpAa1PLmXY10sDdqBqr54Ww5AthG7zxJYa0MYr9p7bPFnK/uqjCj06y7JfHwAX3AhhA==
现在需要将这个字符串转化成原始字符串,原始字符串包含许多重要的信息。
我们来看下JAVA是如何实现这个程序的:
System.out.println(new String(ZipUtil.decompressByteArray(Base64.decodeBase64(str.getBytes()))));
其中Base64为commons-codec-1.3.jar包中的一个类。这个包主要包括核心的算法,比如MD5,SHA1等等,还有一些常规加密解密的算法。
而ZipUtil.decompressByteArray的方法实现为:

{
Inflater inflater = new Inflater();
inflater.setInput(abyte0);
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(abyte0.length);
byte abyte1[] = new byte[1024];
while (!inflater.finished())
try
{
int i = inflater.inflate(abyte1);
bytearrayoutputstream.write(abyte1, 0, i);
}
catch (DataFormatException dataformatexception) { }
try
{
bytearrayoutputstream.close();
}
catch (IOException ioexception) { }
return bytearrayoutputstream.toByteArray();
}
得出的结果为:
这个得到具有一定协议的数据格式,这是项目制定的,这里不必多说。
现在我们来看下C#该如何实现它:

public void Base64Test()
{
string baseStr = "eJyVjMENgDAMA1fpBMjnIkp3ZzZEpAa1PLmXY10sDdqBqr54Ww5AthG7zxJYa0MYr9p7bPFnK/uqjCj06y7JfHwAX3AhhA==";
// Base64解码
byte[] baseBytes = Convert.FromBase64String(baseStr);
// Inflater解压
string resultStr = Decompress(baseBytes);
Console.WriteLine(resultStr);
}
/// <summary>
/// Inflater解压
/// </summary>
/// <param name="baseBytes"></param>
/// <returns></returns>
public string Decompress(byte[] baseBytes)
{
string resultStr = string.Empty;
using (MemoryStream memoryStream = new MemoryStream(baseBytes))
{
using (InflaterInputStream inf = new InflaterInputStream(memoryStream))
{
using (MemoryStream buffer = new MemoryStream())
{
byte[] result = new byte[1024];
int resLen;
while ((resLen = inf.Read(result, 0, result.Length)) > 0)
{
buffer.Write(result, 0, resLen);
}
resultStr = Encoding.Default.GetString(result);
}
}
}
return resultStr;
}
其中InflaterInputStream的类来自于ICSharpCode.SharpZipLib.dll中。
得出的结果为:
可以发现得到的结果是和JAVA版一样的,程序得到实现。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2016-03-29 WCF发布后远程访问的域名解析问题
2015-03-29 PowerDesigner一些小技巧