zoukankan      html  css  js  c++  java
  • 文件二进制与String相互转换

    
    
               //转换base64
                OpenFileDialog dialog = new OpenFileDialog();
                //dialog.Filter = "所有文件(*.*)|*.*";
                dialog.CheckFileExists = true;
                dialog.ShowDialog();
                if (!string.IsNullOrEmpty(dialog.FileName))
                {
                    try
                    {
                        byte[] byteArray = FileBinaryConvertHelper.File2Bytes(dialog.FileName);
                        string base64 = Convert.ToBase64String(byteArray);
                        txtContent.Text = base64;
                txtContent.Focus();
                txtContent.SelectAll(); }
    catch (Exception ex) { MessageBox.Show(ex.Message); } }
    
    
                //解转换base64 
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.Filter = "所有文件(*.*)|*.*";
                dialog.ShowDialog();
                if (!string.IsNullOrEmpty(dialog.FileName))//可以上传压缩包.zip 或者jar包
                {
                    try
                    {
                        byte[] byteArray = Convert.FromBase64String(txtContent.Text); 
                        FileBinaryConvertHelper.Bytes2File(byteArray,dialog.FileName);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }


    ///
    <summary> /// 工具类:文件与二进制流间的转换 /// </summary> public class FileBinaryConvertHelper { /// <summary> /// 将文件转换为byte数组 /// </summary> /// <param name="path">文件地址</param> /// <returns>转换后的byte数组</returns> public static byte[] File2Bytes(string path) { if (!System.IO.File.Exists(path)) { return new byte[0]; } FileInfo fi = new FileInfo(path); byte[] buff = new byte[fi.Length]; FileStream fs = fi.OpenRead(); fs.Read(buff, 0, Convert.ToInt32(fs.Length)); fs.Close(); return buff; } /// <summary> /// 将byte数组转换为文件并保存到指定地址 /// </summary> /// <param name="buff">byte数组</param> /// <param name="savepath">保存地址</param> public static void Bytes2File(byte[] buff, string savepath) { if (System.IO.File.Exists(savepath)) { System.IO.File.Delete(savepath); } FileStream fs = new FileStream(savepath, FileMode.CreateNew); BinaryWriter bw = new BinaryWriter(fs); bw.Write(buff, 0, buff.Length); bw.Close(); fs.Close(); }

    txtContent.Focus();                    txtContent.SelectAll();

  • 相关阅读:
    分布式ID方案
    架构、分布式、微服务
    hexo+GithubPages创建自己的blog
    网络管理基本命令
    jvm-内存模型和一些eclipse调优参数
    JVM-运行时数据区
    JVM-类加载机制
    互联网架构演变过程
    jdk 1.7 新增
    【王的技法0001】机器数、真值、原码、反码、补码总结
  • 原文地址:https://www.cnblogs.com/lee2011/p/6704199.html
Copyright © 2011-2022 走看看