C# 文件与字符串的互转

嗯,就是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,所以如果是单纯的要操作文件的,只需要对文件进行流操作即可。

由简入繁,拿来即用

更多精彩,请关注微信公众号:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值