142

タイトルはそれをすべて言います:

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

編集: 作業例ははるかに単純です (@TS のおかげで):

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

ありがとう!

4

4 に答える 4

360

何らかの理由でファイルを base-64 文字列に変換したい場合。インターネット経由で渡したい場合など...これを行うことができます

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

それに応じて、ファイルに読み戻します。

Byte[] bytes = Convert.FromBase64String(b64Str);
File.WriteAllBytes(path, bytes);
于 2014-09-18T18:16:52.037 に答える