Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fail to convert base64 string when using TryFromBase64String

I receive a Guid as a base64 string. By using the Convert.FromBase64String(b64), the conversion is working well, then I try to use the Convert.TryFromBase64String(b64) but in that case, the method return false and my byte array stays empty

var dataString = "kADs1tnSQ+2ehpdtUAK/Jg==";
// output: d6ec0090-d2d9-ed43-9e86-976d5002bf26
Console.WriteLine(new Guid(Convert.FromBase64String(dataString)));

Span<byte> bytes = new();
bool success = Convert.TryFromBase64String(dataString, bytes, out int _);

// output: False, then FormatException
Console.WriteLine(success);
Console.WriteLine(new Guid(success ? bytes : Convert.FromHexString(dataString)));

I guess my problem is with the initialization of the Span, because if I use new byte[16], it is working, but is it safe to write it using a fixed size of 16?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should provide bytes with allocated space, e.g.

// 16 bytes to store parsed GUID
byte[] bytes = new byte[16];

bool success = Convert.TryFromBase64String(dataString, bytes, out int _);

Similar, if you want to use Span:

// Span of the array which allocates 16 bytes to store GUID
var bytes = new byte[16].AsSpan();

bool success = Convert.TryFromBase64String(dataString, bytes, out int _);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading