2014-09-18 71 views
47

的標題說明了一切:C#轉換文件到Base64String,然後再返回

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

謝謝!

+0

你可以用」只要改變一個壓縮文件的內容。您必須在步驟1中解壓縮文件,而不是直接按照原樣讀取它。然後第5步同樣需要重新壓縮數據,而不是直接寫出字節。 – itsme86 2014-09-18 18:10:19

+0

幸運的是,由於沒有實際操作文件本身(基本上只是將它從A點移動到B點),此特定任務不需要任何(de /)壓縮 – darkpbj 2014-09-18 18:29:21

回答

123

如果你想出於某種原因將你的文件轉換爲base-64字符串。就像如果你想通過互聯網來傳遞,等等......你可以做到這一點

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

相應的,讀迴文件:

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

明確爲日光,謝謝 – 2017-03-22 04:40:20

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

encode a file into base64 format in java

+1

雖然此代碼可能會回答這個問題提供了關於如何和/或爲何解決問題的附加背景,可以提高答案的長期價值。請閱讀此[如何回答](http://stackoverflow.com/help/how-to-answer)以提供高質量的答案。 – thewaywewere 2017-06-17 11:19:02

+0

爲什麼我們再次需要'java'如果OP使用'c#'? – 2017-09-07 19:05:18

相關問題