德code的base64 FILESTREAM与FromBase64Transform [英] Decode base64 filestream with FromBase64Transform

查看:141
本文介绍了德code的base64 FILESTREAM与FromBase64Transform的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的<一个href=\"https://msdn.microsoft.com/en-us/library/system.security.cryptography.frombase64transform%28v=vs.110%29.aspx\"相对=nofollow>例如从MSDN 的似乎读取整个文件到内存中。我不希望出现这种情况。该文件应该由块处理的块。因此,我试图重写例如:

The example from MSDN seems to read the whole file into memory. I don't want that. The file should be processed block by block. Therefore I tried to rewrite the example:

using (FromBase64Transform myTransform = new FromBase64Transform (FromBase64TransformMode.IgnoreWhiteSpaces)) {
    byte[] transformBuffer = new byte[myTransform.OutputBlockSize];

    using (FileStream inputFile = File.OpenRead("/path/to/file/47311.b64")) {
        using(FileStream outputFile = File.OpenWrite("/path/to/file/47311.jpg")){
            int bytesRead;
            byte[] inputBuffer = new byte[4096];
            while ((bytesRead = inputFile.Read (inputBuffer, 0, 4096)) > 0) {
                int bytesWritten = myTransform.TransformBlock (inputBuffer, 0, 4, transformBuffer, 0);
                outputFile.Write (transformBuffer, 0, bytesWritten);
            }

            myTransform.Clear ();
        }
    }
}

但图像无法打开。我做错了吗?

But the image can't be opened. What I'm doing wrong?

推荐答案

我相信这行是错误:

int bytesWritten = myTransform.TransformBlock (inputBuffer, 0, 4, transformBuffer, 0);

您正在改变4个字节,不管你有多少字节读取。我怀疑你想要的:

You're transforming 4 bytes, regardless of how many bytes you've read. I suspect you want:

int bytesWritten = myTransform.TransformBlock (inputBuffer, 0, bytesRead, transformBuffer, 0);

您可能需要更改 transformBuffer 的大小虽然 - 如果你正在读多达每次迭代的base64 4K的数据,则需要高达3K每明文数据迭代。

You may need to change the size of transformBuffer though - if you're reading up to 4K of base64 data per iteration, you need up to 3K for plaintext data per iteration.

有一个简单的选择,但是,很可能会使用转换来创建一个的CryptoStream ,从输入流中读取,然后使用流。 CopyTo从来写入的FileStream

A simpler option, however, would probably be to create a CryptoStream using the transform, reading from the input stream, and then using Stream.CopyTo to write to a FileStream.

这篇关于德code的base64 FILESTREAM与FromBase64Transform的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆