本篇内容介绍了“怎么用C#实现文件与字符串互转”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
实现功能
将文件与为字符串互转
开发环境
开发工具: 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,所以如果是单纯的要操作文件的,只需要对文件进行流操作即可。