简体   繁体   中英

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). The problem is that whenever the database is about 300MB I get an OutOfMemory exception on the 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.

Base64 encodes each sequence of 6 bits into one character. (Hence the name: 2^6 = 64 possible characters.)

4 such characters therefore align to exactly 3 bytes (24 bits).

In other words, the size of your chunks must be a multiple of 3: 3 bytes, or 6 bytes, or 300 bytes...

base64 will always pad to multiple of 4 chars. I think as long as you chop in N*4 sized chunks you are fine.

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

为什么不这样做:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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