Test If String Is a Guid Without Throwing Exceptions

Test if string is a guid without throwing exceptions?

Performance Benchmarks

Catch exception:
10,000 good: 63,668 ticks
10,000 bad: 6,435,609 ticks

Regex Pre-Screen:
10,000 good: 637,633 ticks
10,000 bad: 717,894 ticks

COM Interop CLSIDFromString
10,000 good: 126,120 ticks
10,000 bad: 23,134 ticks

COM Intertop (Fastest) Answer:

/// <summary>
/// Attempts to convert a string to a guid.
/// </summary>
/// <param name="s">The string to try to convert</param>
/// <param name="value">Upon return will contain the Guid</param>
/// <returns>Returns true if successful, otherwise false</returns>
public static Boolean TryStrToGuid(String s, out Guid value)
{
//ClsidFromString returns the empty guid for null strings
if ((s == null) || (s == ""))
{
value = Guid.Empty;
return false;
}

int hresult = PInvoke.ObjBase.CLSIDFromString(s, out value);
if (hresult >= 0)
{
return true;
}
else
{
value = Guid.Empty;
return false;
}
}

namespace PInvoke
{
class ObjBase
{
/// <summary>
/// This function converts a string generated by the StringFromCLSID function back into the original class identifier.
/// </summary>
/// <param name="sz">String that represents the class identifier</param>
/// <param name="clsid">On return will contain the class identifier</param>
/// <returns>
/// Positive or zero if class identifier was obtained successfully
/// Negative if the call failed
/// </returns>
[DllImport("ole32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true)]
public static extern int CLSIDFromString(string sz, out Guid clsid);
}
}

Bottom line: If you need to check if a string is a guid, and you care about performance, use COM Interop.

If you need to convert a guid in String representation to a Guid, use

new Guid(someString);

How to validate Guid in .net

Guid's are unique 99.99999999999999999999999999999999% of the time.

It depends on what you mean by validate?

Code to determine that a Guid string is in fact a Guid, is as follows:

private static Regex isGuid = 
new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);

internal static bool IsGuid(string candidate, out Guid output)
{
bool isValid = false;
output = Guid.Empty;

if(candidate != null)
{

if (isGuid.IsMatch(candidate))
{
output=new Guid(candidate);
isValid = true;
}
}

return isValid;
}

How to validate GUID is a GUID

See if these helps :-

  1. Guid.Parse - Docs
Guid guidResult = Guid.Parse(inputString)

  1. Guid.TryParse - Docs
bool isValid = Guid.TryParse(inputString, out guidOutput)

What is the best way to know if a string is a long or a Guid?

The quick answer is obvious, for example trying to parse a Guid and it
if fails, try to parse a long, but. Is there any good way (elegant
solution) to know if a certain string is a long or a Guid?

No. long.TryParse and Guid.TryParse is the way to go. Another possibility is to test if the string contains - but not in the beginning:

someString.IndexOf("-") > 1

This is a strong indication that this string is not an Int64. It could be a Guid. But it could be anything else. Of course if you know that there can only be Guids and longs in this file it could be a strong indication.

How do I detect if a Guid? is in a ListGuid?

Let's examine your code. What it really says without the syntactic sugar is:

Nullable<Guid> x = new Nullable<Guid>(new Guid());
List<Nullable<Guid>> y = new List<Nullable<Guid>>();
y.Add(x);

Explanation

Nullable<> is actually a struct, so it's not really ever null; only its Value property has a chance of being null, but since its underlying type (Guid) is also a struct, nothing in your list is ever really null.

So why did I explain that? Well, when it comes time for List<>.Contains() to do its magic, the conditions of the combination of the two struct's Equals() methods are determining that your empty Guids don't equal.

The nullable equality operator that takes two nullable guids is applicable in this situation, will be called, and will always return false.

Source

How do we fix it?

Since having Nullable in your solution is pretty useless, I would refactor your code to get rid of it. Guid instead has a handy-dandy Empty property we can use instead:

Guid x = Guid.Empty;
List<Guid> y = new List<Guid>();
y.Add(x);

Console.WriteLine(y.Contains(x)); // True
Console.WriteLine(y.Contains(Guid.Empty)); // True

See the above in action: Ideone

Again, check out this post from Eric Lippert for more information.

Update:

If you're looking for all null (or Empty) items in the list, perhaps it would make more sense to check for items x in the list where x.HasValue is false:

var myList = new List<Guid>();
... /* add to myList */
var theEmpties = myList.Where(x => x == Guid.Empty);

Extract GUID from line in C#

Yes, you can. Cause you return only the first match of regex, you can use Regex.Match instead of Regex.Matches.

private static string RetrieveGUID2(string[] lines)
{
foreach (var line in lines)
{
var match = Regex.Match(line, @"[{(]?[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?");
if (match.Success)
return match.Value;
}

return null;
}

Guid constructor throwing formatException on apparently valid string

Well, it looks like it's a valid GUID string with 32 hex digits, but it is not.

When copying your string into an editor I see that the very last character is unicode point 8207, Rigth to left mark. It's an unprintable character, but it's there. Try this instead:

new Guid("31033981b158e31187e700155d094430");

You can't see the difference in your browser, but it will work - I removed the unprintable character from your string.



Related Topics



Leave a reply



Submit