C# Method like Base64String, but only alphanumeric

2019-03-25 14:49发布

is there any C# method that works similar to Convert.ToBase64String but doesn't generate anything except alphanumeric output?

Thanks!

6条回答
冷血范
2楼-- · 2019-03-25 15:24

I was searching for a such like encoder and I used https://github.com/renmengye/base62-csharp/

It's an encoder/decoder in "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" character space range.

I just wrapped its methods with

System.Text.Encoding.UTF8.GetBytes(plainText); and System.Text.Encoding.UTF8.GetString(decoded);

calls to allow it to work easily with strings.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-03-25 15:28

You can use BitConverter.ToString() which will give you a hex string. However the resulting strings will be longer than Base64 encoding.

查看更多
叛逆
4楼-- · 2019-03-25 15:40

You're probably looking at using something like Base32 encoding then. There is a Base32 encoder/decoder for C# here by Michael Giagnocavo. It uses a combination of capitalized letters and numbers.

There's also a related discussion on StackOverflow here.

EDIT: And if by any chance this is for URL-safe related Base64 encoding, just do Base64 and replace "+" with "-" and "/" with "_". But I'm guessing, you may not want it for that.

查看更多
Ridiculous、
5楼-- · 2019-03-25 15:42

The answers are a bit outdated now. For the benefit of future searchers: The best way to handle this now in C# is:

byte[] b; // fill your byte array somehow
string s = System.Web.HttpServerUtility.UrlTokenEncode(b);

This returns a Base64-encoded string that is URL-safe (which is what you said you were really after in the comments to your question).

You can then decode it again using, you guessed it:

byte[] b = System.Web.HttpServerUtility.UrlTokenDecode(s);
查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-03-25 15:43

A common variant of base-64 (for use on query-string) is to use '-' and '_' in place of '+' and '/'. Perhaps a bit of Replace(...) at each end would do the job?

查看更多
仙女界的扛把子
7楼-- · 2019-03-25 15:48

you can replace + or slash with some predefined string if possible.

查看更多
登录 后发表回答