Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert string to GUID in C#.NET [duplicate]

Why would the cast (to a System.Guid type) statement be invalid (second line in try block)?

For example, suppose I have a string with a value of "5DD52908-34FF-44F8-99B9-0038AFEFDB81". I'd like to convert that to a GUID. Is that not possible?

    Guid ownerIdGuid = Guid.Empty;     try     {         string ownerId = CallContextData.Current.Principal.Identity.UserId.ToString();         ownerIdGuid = (Guid)ownerId;     }     catch     {         // Implement catch     } 
like image 811
MacGyver Avatar asked Aug 25 '11 22:08

MacGyver


People also ask

How to convert string in GUID?

Program to convert string into guid in . Net Framework using C# Guid. Parse method. This method contains two parameters string as an input and if this method returns true then result parameter contains a valid Guid and in case false is returned result parameter will contain Guid.

Is a GUID a string?

A GUID is a 16-byte (128-bit) number, typically represented by a 32-character hexadecimal string.

What does GUID parse do?

The Parse method trims any leading or trailing white space from input and converts the string representation of a GUID to a Guid value. This method can convert strings in any of the five formats produced by the ToString(String) and ToString(String, IFormatProvider) methods, as shown in the following table.

How do you convert GUID to int?

An integer uses 32 bits, whereas a GUID is 128 bits - therefore, there's no way to convert a GUID into an integer without losing information, so you can't convert it back. EDIT: you could perhaps store the GUID into a GUIDs table where you assign each a unique integer ID.


2 Answers

Try this:

Guid ownerIdGuid = Guid.Empty;             try {     string ownerId = CallContextData.Current.Principal.Identity.UserId.ToString();     ownerIdGuid = new Guid(ownerId); } catch {     // implement catch  } 
like image 177
Kiley Naro Avatar answered Oct 14 '22 01:10

Kiley Naro


Try this:

ownerIdGuid = Guid.Parse(ownerId); 

ownerId is a string, you cannot cast it to a Guid directly.

like image 45
BrokenGlass Avatar answered Oct 14 '22 01:10

BrokenGlass