简体   繁体   English

如何安全地转换块中的ToBase64String?

[英]How to safely convert `ToBase64String` in chunks?

This is my current code: 这是我目前的代码:

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        CloseConnection();
        using (Stream source = File.Open(DataBaseFileName, FileMode.Open))
        {
            byte[] buffer = new byte[source.Length];
            source.Read(buffer, 0, (int)source.Length);
            writer.WriteString(Convert.ToBase64String(buffer));
        }
        OpenConnection();
    }

What this does is embed a database into an XML file (this method belongs to the class of a field in another class that is the one being serialized). 这样做是将数据库嵌入到XML文件中(此方法属于另一个类中正在序列化的类中的字段的类)。 The problem is that whenever the database is about 300MB I get an OutOfMemory exception on the byte[] buffer = new byte[source.Length]; 问题是每当数据库大约300MB时,我在byte[] buffer = new byte[source.Length];上得到一个OutOfMemory异常byte[] buffer = new byte[source.Length]; line. 线。 So I guees I need to do it on chunks. 所以我猜我需要在大块上做。 But I'm not sure how would that be. 但我不确定那是怎么回事。 I think these chunks would need to be of a particular size. 我认为这些块需要具有特定的大小。 Also, I think Convert.ToBase64String will add two "==" symbols at the end of the string so I will probably have to erase them each time until the last one. 此外,我认为Convert.ToBase64String将在字符串的末尾添加两个“==”符号,因此我可能每次都要删除它们,直到最后一个。

Base64 encodes each sequence of 6 bits into one character. Base64将每个6位序列编码为一个字符。 (Hence the name: 2^6 = 64 possible characters.) (因此名称:2 ^ 6 = 64个可能的字符。)

4 such characters therefore align to exactly 3 bytes (24 bits). 因此,4个这样的字符恰好对准3个字节(24位)。

In other words, the size of your chunks must be a multiple of 3: 3 bytes, or 6 bytes, or 300 bytes... 换句话说,块的大小必须是3:3字节,或6字节或300字节的倍数......

base64 will always pad to multiple of 4 chars. base64将始终填充4个字符的多个。 I think as long as you chop in N*4 sized chunks you are fine. 我想只要你砍下N * 4大小的块你就可以了。

找到一个Base64流类: 链接文本

为什么不这样做:

writer.WriteString(Convert.ToBase64String(File.ReadAllBytes(DataBaseFileName)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM