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

编程入门 行业动态 更新时间:2024-10-26 08:28:30
本文介绍了将文件转换为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:47,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1634912.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:转换为   文件   Base64String

    发布评论

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

    >www.elefans.com

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