将文件转换为 Base64String 并再次返回

编程入门 行业动态 更新时间:2024-10-26 06:33:21
本文介绍了将文件转换为 Base64String 并再次返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

标题说明了一切:

  • 我在 tar.gz 存档中读到这样的文件
  • 将文件分解为字节数组
  • 将这些字节转换为 Base64 字符串
  • 将该 Base64 字符串转换回字节数组
  • 将这些字节写回到新的 tar.gz 文件中
  • 我可以确认两个文件的大小相同(以下方法返回 true),但我无法再提取副本版本.

    I can confirm that both files are the same size (the below method returns true) but I can no longer extract the copy version.

    我错过了什么吗?

    Boolean MyMethod(){ using (StreamReader sr = new StreamReader("C:...file.tar.gz")) { String AsString = sr.ReadToEnd(); byte[] AsBytes = new byte[AsString.Length]; Buffer.BlockCopy(AsString.ToCharArray(), 0, AsBytes, 0, AsBytes.Length); String AsBase64String = Convert.ToBase64String(AsBytes); byte[] tempBytes = Convert.FromBase64String(AsBase64String); File.WriteAllBytes(@"C:...file_copy.tar.gz", tempBytes); } FileInfo orig = new FileInfo("C:...file.tar.gz"); FileInfo copy = new FileInfo("C:...file_copy.tar.gz"); // Confirm that both original and copy file have the same number of bytes return (orig.Length) == (copy.Length); }

    工作示例要简单得多(感谢@T.S.):

    The working example is much simpler (Thanks to @T.S.):

    Boolean MyMethod(){ byte[] AsBytes = File.ReadAllBytes(@"C:...file.tar.gz"); String AsBase64String = Convert.ToBase64String(AsBytes); byte[] tempBytes = Convert.FromBase64String(AsBase64String); File.WriteAllBytes(@"C:...file_copy.tar.gz", tempBytes); FileInfo orig = new FileInfo(@"C:...file.tar.gz"); FileInfo copy = new FileInfo(@"C:...file_copy.tar.gz"); // Confirm that both original and copy file have the same number of bytes return (orig.Length) == (copy.Length); }

    谢谢!

    推荐答案

    如果您出于某种原因想要将文件转换为 base-64 字符串.就像如果你想通过互联网传递它等等......你可以这样做

    If you want for some reason to convert your file to base-64 string. Like if you want to pass it via internet, etc... you can do this

    Byte[] bytes = File.ReadAllBytes("path"); String file = Convert.ToBase64String(bytes);

    相应地,读回文件:

    Byte[] bytes = Convert.FromBase64String(b64Str); File.WriteAllBytes(path, bytes);

    更多推荐

    将文件转换为 Base64String 并再次返回

    本文发布于:2023-11-26 19:33:30,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1634911.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:转换为   文件   Base64String

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!