.NET GUID uppercase string format

跟風遠走 提交于 2019-12-06 20:28:58

问题


I need to format my GUIDs in the dashed format, all uppercase. I know using myGuid.ToString("D") or String.Format("{0:D}", myGuid) gives the dashed format, but using an uppercase D as opposed to a lower-case d doesn't give me an uppercased GUID like I thought it would. Is there a way to do this without doing anything crazy, or do I just need to call myGuid.ToString().ToUpper()?


回答1:


do I just need to call myGuid.ToString().ToUpper()

Yep. You could go to the effort of creating a custom IFormatProvider, but it doesn't seem worth it here.




回答2:


Note that RFC 4122, which defines the UUID specification, stipulates that output hex characters should be in lowercase when converting the structure to a string:

  The hexadecimal values "a" through "f" are output as
  lower case characters and are case insensitive on input.

This may explain why the Guid structure does not support outputting directly as an uppercase string.

Since the ToString format provider parameter is ignored, the only alternative (without simply converting the string to uppercase) would be to directly manipulate the bytes, while taking care to preserve endianness. Simply converting to uppercase (either directly or through an extension method) is probably far more straightforward.




回答3:


I don't think you have any other choice than to just do myGuid.ToString().ToUpper(). Although, you could always write an extension method, perhaps something like ToUpperString, but I don't think there is anything built into the system.




回答4:


Assuming you have a class that holds your Guid and you would like to retain the typed Guid, you could do something like this:

public Guid Identifier { get; set; }

public String FormattedIdentifier => Identifier.ToString().ToUpper();


来源:https://stackoverflow.com/questions/6868300/net-guid-uppercase-string-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!