分享

C# 文件与字符串的互转

 Csharp小记 2023-10-29 发布于江苏

嗯,就是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;     } } //调用文件转base64 private void btnBase64_Click(object sender, EventArgs e) {     textBox2.Text = FileToBase64String(textBox1.Text);     MessageBox.Show("成功"); } //调用base64转文件 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("成功");     } }
//文件转base64 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; }
}
//base64转文件 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,所以如果是单纯的要操作文件的,只需要对文件进行流操作即可。

由简入繁,拿来即用

后续精彩,持续关注

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多