C# 方法,如 Base64String,但仅限字母数字(无加号或斜杠)
是否有任何 C# 方法的工作原理与 Convert.ToBase64String 类似,但除了字母数字输出外不生成任何内容?
谢谢!
is there any C# method that works similar to Convert.ToBase64String but doesn't generate anything except alphanumeric output?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
那么您可能正在考虑使用 Base32 编码之类的东西。 有一个用于 C# 的 Base32 编码器/解码器这里 迈克尔·贾格诺卡沃 (Michael Giagnocavo)。 它使用大写字母和数字的组合。
StackOverflow 上还有此处的相关讨论。
编辑:如果万一这是与 URL 安全相关的 Base64 编码,只需执行 Base64 并将“+”替换为“-”,将“/”替换为“_”。 但我猜你可能不希望这样。
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.
Base-64 的常见变体(用于查询字符串)是使用“-”和“_”代替“+”和“/”。 也许在每一端添加一点
Replace(...)
就可以完成这项工作?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?如果可能的话,您可以用一些预定义的字符串替换 + 或斜杠。
you can replace + or slash with some predefined string if possible.
我正在寻找类似的编码器,我使用 https://github.com/renmengye/base62-csharp /
它是“0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz”字符空间范围内的编码器/解码器。
我只是用
System.Text.Encoding.UTF8.GetBytes(plainText); 包装了它的方法
和
System.Text.Encoding.UTF8.GetString(decoded);
调用以使其能够轻松处理字符串。
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.
您可以使用 BitConverter.ToString() 它将为您提供一个十六进制字符串。 但是,生成的字符串将比 Base64 编码长。
You can use BitConverter.ToString() which will give you a hex string. However the resulting strings will be longer than Base64 encoding.
现在的答案有点过时了。 为了未来搜索者的利益:现在在 C# 中处理此问题的最佳方法是:
这将返回一个 URL 安全的 Base64 编码字符串(这就是您在问题评论中所说的真正想要的)。
然后你可以使用你猜到的再次解码它:
The answers are a bit outdated now. For the benefit of future searchers: The best way to handle this now in C# is:
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: