C# 生成不带连字符的 GUID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8877460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:55:20  来源:igfitidea点击:

generating GUID without hyphen

c#winforms

提问by Harish Kumar

I am generating a GUID using the following statement in my code

我在代码中使用以下语句生成 GUID

byte[ ] keyBytes = Encoding.UTF8.GetBytes( Guid.NewGuid( ).ToString( ).Substring( 0, 12 ) );

But, when a GUID is generated, I find that it contains the hyphen character too. How do I go about in generating a GUID with only letters (upper case and lower case) and numbers? I do not want the hyphen. Can someone give me so idea?

但是,当生成 GUID 时,我发现它也包含连字符。如何生成仅包含字母(大写和小写)和数字的 GUID?我不想要连字符。有人可以给我这样的想法吗?

采纳答案by Christian.K

Note that you are talking about the (canonical) string representation of a Guid. The Guid itself is actually a 128-bit integer value.

请注意,您正在谈论 Guid 的(规范)字符串表示形式。Guid 本身实际上是一个 128 位整数值。

You can use the "N" specifier with the Guid.ToString(String)overload.

您可以在Guid.ToString(String)重载中使用“N”说明符。

Guid.NewGuid().ToString("N");

By default letters are lowercase. A Guid with only uppercase letters can only be achieved by manually converting them all to uppercase, example:

默认情况下字母是小写的。只有大写字母的 Guid 只能通过手动将它们全部转换为大写来实现,例如:

Guid.NewGuid().ToString("N").ToUpper();

A guid with only either letter or digits makes no sense. A guid string representation is hexadecimal, and thus will always (well most likely) contain both.

只有字母或数字的 guid 没有任何意义。guid 字符串表示是十六进制的,因此将始终(很可能)包含两者。

回答by Bonshington

Guid.NewGuid().ToString().Replace("-", string.Empty)