嗯,就是BASE64,不用多想,本來(lái)計(jì)劃是要跟上一篇字符串壓縮一起寫的,用來(lái)實(shí)現(xiàn)將一個(gè)文件可以用json或者text等方式進(jìn)行接口之間的傳輸,為了保證傳輸效率,所以對(duì)生成的字符串進(jìn)行進(jìn)一步壓縮。但是由于不能上傳完整源代碼,所以就還是分開(kāi)寫了,方便展示實(shí)現(xiàn)效果以及功能的單獨(dú)使用。
實(shí)現(xiàn)功能:
開(kāi)發(fā)環(huán)境:
開(kāi)發(fā)工具:Visual Studio 2013
.NET Framework版本:4.5
實(shí)現(xiàn)代碼:
private void btnPath_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
}
}
private void btnBase64_Click(object sender, EventArgs e)
{
textBox2.Text = FileToBase64String(textBox1.Text);
MessageBox.Show("成功");
}
private void btnFile_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "文件|*" + textBox1.Text.Substring(textBox1.Text.LastIndexOf('.'));
if (sfd.ShowDialog() == DialogResult.OK)
{
Base64StringToFile(textBox2.Text, sfd.FileName);
MessageBox.Show("成功");
}
}
public string FileToBase64String(string path)
{
try
{
string data = "";
using (MemoryStream msReader = new MemoryStream())
{
using (FileStream fs = new FileStream(path, FileMode.Open))
{
byte[] buffer = new byte[1024];
int readLen = 0;
while ((readLen = fs.Read(buffer, 0, buffer.Length)) > 0)
{
msReader.Write(buffer, 0, readLen);
}
}
data = Convert.ToBase64String(msReader.ToArray());
}
return data;
}
catch (Exception ex)
{
throw ex;
}
}
public void Base64StringToFile(string base64String, string path)
{
try
{
using (MemoryStream stream = new MemoryStream(Convert.fromBase64String(base64String)))
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrcreate, FileAccess.Write))
{
byte[] b = stream.ToArray();
fs.Write(b, 0, b.Length);
}
}
}
catch (Exception ex)
{
throw ex;
}
}
實(shí)現(xiàn)效果:
觀察代碼可以發(fā)現(xiàn),其實(shí)在上一篇做壓縮的時(shí)候,也是用到了base64,所以如果是單純的要操作文件的,只需要對(duì)文件進(jìn)行流操作即可。
該文章在 2023/2/27 10:11:20 編輯過(guò)