【问题标题】:Converting file into Base64String and back again将文件转换为 Base64String 并再次返回
【发布时间】:2014-11-13 04:34:42
【问题描述】:

标题说明了一切:

  1. 我在 tar.gz 存档中读到这样的文件
  2. 将文件分解为字节数组
  3. 将这些字节转换为 Base64 字符串
  4. 将该 Base64 字符串转换回字节数组
  5. 将这些字节写回到新的 tar.gz 文件中

我可以确认两个文件的大小相同(以下方法返回 true),但我无法再提取副本版本。

我错过了什么吗?

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.):

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);
}

谢谢!

【问题讨论】:

  • 你不能像那样改变压缩文件的内容。您必须在步骤 1 中解压缩文件,而不是直接按原样读入。然后第 5 步同样必须重新压缩数据,而不是直接写出字节。
  • 幸运的是,由于没有对文件本身进行实际操作(基本上只是将其从 A 点移动到 B),因此此特定任务不需要任何 (de/) 压缩

标签: c# base64 streamreader system.io.fileinfo


【解决方案1】:

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

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

相应地,读回文件:

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

【讨论】:

  • 感谢您提供的信息,我尝试按照下面的答案进行操作,但没有帮助,但这似乎通过简单的 openFileDialog 解决了我的问题
  • 如果 ToBase64String 返回 System.OutOfMemoryException 怎么办?如何针对大文件和有限的内存进行优化
  • @OlorunfemiAjibulu 然后我怀疑,你需要使用流。或者把绳子分成几部分。有一次,我为保存加密块的大文件编写了自定义加密。我们添加了 4 个字节来保存块大小的整数值。这样我们就知道要阅读这么多职位
  • 有趣的@TaylorSpark。我使用流,我很好。
【解决方案2】:
private String encodeFileToBase64Binary(File file){    
String encodedfile = null;  
try {  
    FileInputStream fileInputStreamReader = new FileInputStream(file);  
    byte[] bytes = new byte[(int)file.length()];
    fileInputStreamReader.read(bytes);  
    encodedfile = Base64.encodeBase64(bytes).toString();  
} catch (FileNotFoundException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
} catch (IOException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
}  
    return encodedfile;  
}

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。请阅读此how-to-answer 以提供高质量的答案。
  • 如果 OP 使用 c#,为什么我们还需要 java
  • @T.S.为什么我们需要 java?
【解决方案3】:

VB.NET 中的另一个工作示例:

Public Function base64Encode(ByVal myDataToEncode As String) As String
    Try
        Dim myEncodeData_byte As Byte() = New Byte(myDataToEncode.Length - 1) {}
        myEncodeData_byte = System.Text.Encoding.UTF8.GetBytes(myDataToEncode)
        Dim myEncodedData As String = Convert.ToBase64String(myEncodeData_byte)
        Return myEncodedData
    Catch ex As Exception
        Throw (New Exception("Error in base64Encode" & ex.Message))
    End Try
    '
End Function

【讨论】:

    【解决方案4】:

    对于 Java,请考虑使用Apache Commons FileUtils

    /**
     * Convert a file to base64 string representation
     */
    public String fileToBase64(File file) throws IOException {
        final byte[] bytes = FileUtils.readFileToByteArray(file);
        return Base64.getEncoder().encodeToString(bytes);
    }
    
    /**
     * Convert base64 string representation to a file
     */
    public void base64ToFile(String base64String, String filePath) throws IOException {
        byte[] bytes = Base64.getDecoder().decode(base64String);
        FileUtils.writeByteArrayToFile(new File(filePath), bytes);
    }
    

    【讨论】:

    • 问题在C#下标记,如果您提供C#的解决方案会更好。
    猜你喜欢
    • 2015-01-19
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 2011-01-13
    • 2016-04-02
    • 2014-05-26
    相关资源
    最近更新 更多