Cannot convert string to GUID in C#.NET

MacGyver picture MacGyver · Aug 26, 2011 · Viewed 96.8k times · Source

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
    }

Answer

Kiley Naro picture Kiley Naro · Aug 26, 2011

Try this:

Guid ownerIdGuid = Guid.Empty;            
try
{
    string ownerId = CallContextData.Current.Principal.Identity.UserId.ToString();
    ownerIdGuid = new Guid(ownerId);
}
catch
{
    // implement catch 
}