C# 文件与字符串的互转
|
admin
2023年2月27日 10:11
本文热度 1852
|
嗯,就是BASE64,不用多想,本来计划是要跟上一篇字符串压缩一起写的,用来实现将一个文件可以用json或者text等方式进行接口之间的传输,为了保证传输效率,所以对生成的字符串进行进一步压缩。但是由于不能上传完整源代码,所以就还是分开写了,方便展示实现效果以及功能的单独使用。
实现功能:
开发环境:
开发工具:Visual Studio 2013
.NET Framework版本:4.5
实现代码:
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; } }
实现效果:

观察代码可以发现,其实在上一篇做压缩的时候,也是用到了base64,所以如果是单纯的要操作文件的,只需要对文件进行流操作即可。
该文章在 2023/2/27 10:11:20 编辑过