Encoding string to Base64 / UTF8

Sometimes you need to convert strings to Base64, for example in security components. The function below does this:

public string stringToBase64(string s)
        byte[] bytes = new byte[s.Length];
        bytes = System.Text.Encoding.UTF8.GetBytes(s);
        return Convert.ToBase64String(bytes);
    catch (Exception e)
        throw new Exception("stringToBase64 error: " + e.Message);
Author Dave Howard

I have been involved in IT development for the last 10 years - a lot of it around desktop applications and telecoms.


Adam Liechty said:

Thanks for the post. But the following line is unnecessary:

--> byte[] bytes = new byte[s.Length];

"bytes" gets completely overwritten by the next line.

08/Apr/2008 23:52 PM

theplague said:

this is not utf-8

11/Mar/2010 18:16 PM

Add Comment


Your comment has been received and will be shown once it passes moderation.