I know how to encode / decode a simple string to / from base64.
But how would I do that if the data is already been written to a FileStream object. Let's say I have only access to the FileStream object not to the previously stored original data in it. How would I encode a FileStream to base64 before I flush the FileStream to a file.
Ofc I could just open my file and encode / decode it after I have written the FileStream to the file, but I would like to do this all in one single step without doing two file operations one after another. The file could be larger and it would also take double time to load, encode and save it again after it was just saved a short time before.
Maybe someone of you knows a better solution? Can I convert the FileStream to a string, encode the string and then convert the string back to a FileStream for example or what would I do and how would such a code look like?
If we were to Base64 encode a string we would follow these steps: Take the ASCII value of each character in the string. Calculate the 8-bit binary equivalent of the ASCII values. Convert the 8-bit chunks into chunks of 6 bits by simply re-grouping the digits.
Convert JSON to Base64 World's simplest base64 JSON encoder for web developers and programmers. Just paste your JSON data structure in the form below, press Base64 Encode JSON button, and you get a base64-encoded JSON document.
You will not see any commas, colons, or double quotes in a Base64 encoded string. You will see equals signs since they're used to pad the ending content.
Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. By consisting only of ASCII characters, base64 strings are generally url-safe, and that's why they can be used to encode data in Data URLs.
An easy one as an extension method
public static class Extensions { public static Stream ConvertToBase64(this Stream stream) { byte[] bytes; using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); bytes = memoryStream.ToArray(); } string base64 = Convert.ToBase64String(bytes); return new MemoryStream(Encoding.UTF8.GetBytes(base64)); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With