[C # delicious] What is the Guid ToString format ?,
In daily programming, Guid is commonly used. The most common usage is as follows:
string id = Guid.NewGuid().ToString();
This statement generates a new Guid and converts it to a string, as shown below:
// 10244798-9a34-4155-b1ef-9143f9b1e68a
However, in some cases, we may have some differences in details, such:
- Braces {xxxxxxxx-xxxx-xxxxxxxxxxxx}
- There is no hyphen between xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- Parentheses (xxxxxxxx-xxxx-xxxxxxxxxxxx)
In this case, it is quite troublesome. The most common one is to parse the string generated by the guid, such as adding parentheses or replacing the hyphen with null characters:
var str = guid.ToString();var id = "{" + str + "}";var id2 = str.Replace("-", "");var id3 = "(" + str + ")";
In fact, this is not so troublesome. In ToString, there is an overloaded function:
ToString(String)
You can input a formatted string to output this type of guid.
Example:
var guid = Guid.NewGuid();// 10244798-9a34-4245-b1ef-9143f9b1e68aConsole.WriteLine(guid.ToString("D"));// 102447989a344245b1ef9143f9b1e68aConsole.WriteLine(guid.ToString("N"));// {10244798-9a34-4245-b1ef-9143f9b1e68a}Console.WriteLine(guid.ToString("B"));// (10244798-9a34-4245-b1ef-9143f9b1e68a)Console.WriteLine(guid.ToString("P"));
Note: The values D, N, B, and P are case-insensitive. If an empty string is input, the default D type is used. Exceptions are reported in other cases.
There is also an "X" type found in MSDN, but an exception will pop up when I use it in. NetFx 3.5:
Unprocessed exception: System. formatException: the format string can only be "D", "d", "N", "n", "P", "p", "B", or "B ".
In System. Guid. ToString (String format, IFormatProvider provider)
The article forwarded micro-blog: http://www.cnblogs.com/greenerycn/archive/2010/04/25/guid_tostring_format.html (original)