C# WinForms 字符串压缩与解压缩示例
使用 C# 的 System.IO.Compression 命名空间可以实现字符串的压缩。以下是一个简单的示例代码,演示如何在 WinForms 窗口程序中使用两个文本框,一个用于输入需要压缩的字符串,另一个用于输出压缩后的字符串:
using System;
using System.IO.Compression;
using System.Text;
using System.Windows.Forms;
namespace StringCompression
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCompress_Click(object sender, EventArgs e)
{
string input = txtInput.Text;
byte[] bytes = Encoding.UTF8.GetBytes(input);
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress))
{
gzip.Write(bytes, 0, bytes.Length);
}
byte[] compressedBytes = ms.ToArray();
string compressedString = Convert.ToBase64String(compressedBytes);
txtOutput.Text = compressedString;
}
}
private void btnDecompress_Click(object sender, EventArgs e)
{
string compressedString = txtOutput.Text;
byte[] compressedBytes = Convert.FromBase64String(compressedString);
using (MemoryStream ms = new MemoryStream(compressedBytes))
{
using (GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress))
{
byte[] buffer = new byte[1024];
using (MemoryStream output = new MemoryStream())
{
int read;
while ((read = gzip.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
string decompressedString = Encoding.UTF8.GetString(output.ToArray());
txtInput.Text = decompressedString;
}
}
}
}
}
}
在上面的代码中,我们使用了两个按钮分别处理压缩和解压缩操作。在 btnCompress_Click 方法中,我们首先将输入字符串转换为字节数组,然后使用 GZipStream 进行压缩。压缩后的字节数组再转换为 Base64 编码的字符串,最后输出到文本框中。
在 btnDecompress_Click 方法中,我们做了相反的操作。首先将 Base64 编码的字符串转换为字节数组,然后使用 GZipStream 进行解压缩。解压缩后的字节数组再转换为字符串,最后输出到另一个文本框中。
请注意,由于压缩后的字符串可能包含一些特殊字符,因此我们将其转换为 Base64 编码的字符串进行输出,以确保其能够正确地显示和传输。
原文地址: https://www.cveoy.top/t/topic/lq2m 著作权归作者所有。请勿转载和采集!