简体   繁体   中英

How to cast a STRING to a GUID

I need cast a String to a Guid .

I am using this code but

string myUserIdContent = ((Label)row.FindControl("uxUserIdDisplayer")).Text;
Guid myGuidUserId = new Guid(myUserIdContent); // PROBLEM HERE
MembershipUser mySelectedUser = Membership.GetUser(myGuidUserId);

I receive this error

Exception Details: System.FormatException: Unrecognized Guid format.

What is the proper way to achieve the results?

Use Guid.TryParse .

      string myUserIdContent = ((Label)row.FindControl("uxUserIdDisplayer")).Text;
      Guid myGuidUserId;
      if (Guid.TryParse(myUserIdContent, out myGuidUserId)
      {
          MembershipUser mySelectedUser = Membership.GetUser(myGuidUserId);
      }
      else
      {
          // throw exception and/or inform user
      }

By the looks of that exception, your string isn't correctly formatted. Per MSDN:

A string that contains a GUID in one of the following formats ("d" represents a hexadecimal digit whose case is ignored):

32 contiguous digits:

dddddddddddddddddddddddddddddddd

-or-

Groups of 8, 4, 4, 4, and 12 digits with hyphens between the groups. The entire GUID can optionally be enclosed in matching braces or parentheses:

dddddddd-dddd-dddd-dddd-dddddddddddd

-or-

{dddddddd-dddd-dddd-dddd-dddddddddddd}

-or-

(dddddddd-dddd-dddd-dddd-dddddddddddd)

-or-

Groups of 8, 4, and 4 digits, and a subset of eight groups of 2 digits, with each group prefixed by "0x" or "0X", and separated by commas. The entire GUID, as well as the subset, is enclosed in matching braces:

{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}

All braces, commas, and "0x" prefixes are required. All embedded spaces are ignored. All leading zeros in a group are ignored.

The digits shown in a group are the maximum number of meaningful digits that can appear in that group. You can specify from 1 to the number of digits shown for a group. The specified digits are assumed to be the low-order digits of the group.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM