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

This question already has answers here:
Test if string is a guid without throwing exceptions?
(19 answers)
Closed 5 years ago.
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
}

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

Try this:
ownerIdGuid = Guid.Parse(ownerId);
ownerId is a string, you cannot cast it to a Guid directly.

You cannot cast directly from string to Guid. Instead, use either:
Guid.Parse (throws FormatException on invalid format); or
Guid.TryParse (returns false on invalid format)

Try one of these:
Guid.Parse
Guid.TryParse
Gruid.TryParseExact
in .NET 4.0 (or 3.5)

You need to use Guid.Parse to convert from string to Guid

System.Guid x = new System.Guid("5DD52908-34FF-44F8-99B9-0038AFEFDB81") works and answers what's being asked
(I know this is an old post)

Related

how to use Any(char.IsDigit) to extract the int value [duplicate]

This question already has answers here:
How can I parse the int from a String in C#?
(4 answers)
Closed 3 months ago.
I have this line of code
bool containsInt = "Sanjay 400".Any(char.IsDigit)
What I am trying to do is extract the 400 from the string but
Any(char.IsDigit)
only returns a true value. I am very new to coding and c# especially.
As you already found out, you cannot use Any for extraction.
You would need to use the Where method:
List<char> allInts = "Sanjay 400".Where(char.IsDigit).ToList();
The result will be a list containing all integers/digits from your string.
Ok if you are interested in the value as integer you would need to convert it again to a string and then into an integer. Fortunately string has a nice constructor for this.
char[] allIntCharsArray = "Sanjay 400".Where(char.IsDigit).ToArray();
int theValue = Convert.ToInt32(new string(allIntCharsArray));
If you are using .NET 5 or higher you could also use the new cool TryParse method without extra string conversion:
int.TryParse(allIntCharsArray, out int theValue);
int result = int.Parse(string.Concat("Sanjay 400".Where(char.IsDigit)));
Use the Regex
var containsInt = Convert.ToInt32(Regex.Replace(#"Sanjay 400", #"\D", ""));
Regular expressions allow you to take only numbers and convert them into integers.

How can I convert string to Guid? [duplicate]

This question already has answers here:
Test if string is a guid without throwing exceptions?
(19 answers)
Closed 5 years ago.
I have string type value like "e2ddfa02610e48e983824b23ac955632". I need to add - in this code means convert in Guid.
EntityKey = "e2ddfa02610e48e983824b23ac955632";
Id = (Guid)paymentRecord.EntityKey;
Just a simple creation:
String source = "e2ddfa02610e48e983824b23ac955632";
Guid result = new Guid(source);
You could do :
Guid guid;
if (Guid.TryParse("e2ddfa02610e48e983824b23ac955632", out guid))
{
// succeed...
}
else
{
// failed...
}
Edit : Like #Silvermind said, if you know the format of the input, you can use Guid.TryParseExact with the "N" format in your case.
For parsing the string to a Guid. You can do this:
var guid= "e2ddfa02610e48e983824b23ac955632";
var result= Guid.ParseExact(guid,"N")
Or if you prefer to have it in a try parse. You can also do this:
Guid result;
if(Guid.TryParseExact(guid,"N",out result))
{
//Do something
}
The "N" is a format which indicates that the string will be format with 32 digits without "-"
Reference:
Guid.TryParseExact Method (String, String, Guid)

convert string value to int [duplicate]

This question already has answers here:
Not able to cast string to int. Error msg: Input string was not in a correct format
(6 answers)
Closed 9 years ago.
if (!IsPostBack)
{
string EnquiryID = (Session["Enq_ID"].ToString());
if (EnquiryID != null)
{
int Enquiry = Convert.ToInt32(EnquiryID);
hotelOBJ.FillbyQueryEnquiry1(Enquiry, txtClientph, txtClientAddress );
}
}
there is my code my session is not convert into integer the error is
"Input string was not in a correct format. "
The error says that there might be some characters that can't be converted to Integer in any case like 1234ab contains characters ab which can't be converted to Integer.
What you can do is:
bool result = Int32.TryParse(Session["Enq_ID"].ToString(), out number);
if (result)
{
hotelOBJ.FillbyQueryEnquiry1(number, txtClientph, txtClientAddress );
}
else
{
Console.WriteLine("Attempted conversion of '{0}' failed.",
Session["Enq_ID"].ToString());
}
I think the string that you try to convert to int is empty or it contains characters that is not digits (basically your string does not represent an integer value in a string form). That's why you get that error message.
So at least you have to replace your
if (EnquiryID != null)
with
if(!string.IsNullOrWhiteSpace(EnquiryID))
That's how you will know what if you try to convert variable it at least have something to convert.
And or use Int32.TryParse() function to test (and convert to integer) if the string that you try to convert is an integer.
Use Int32.Parse(). Beware FormatException when parsing, its good to use TryParse first or wrap TryParse in an extension method. Also change your if statement. The way you have it now can result in NullReferenceException if your query string parameter is missing.
if (!IsPostBack)
{
if (Session["Enq_ID"] != null)
{
string EnquiryID = Session["Enq_ID"].ToString();
if (EnquiryID.IsValidInt32())
{
int Enquiry =Int32.Parse(EnquiryID);
hotelOBJ.FillbyQueryEnquiry1(Enquiry, txtClientph, txtClientAddress );
}
}
}
Extension method...
public static bool IsValidInt32(this string value)
{
int result;
return int.TryParse(value, out result);
}

how can i change queryString value to (int) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I convert String to Int?
how can i change queryString value to an (int)
string str_id;
str_id = Request.QueryString["id"];
int id = (int)str_id;
Use Int32.TryParse Method to get int value safely:
int id;
string str_id = Request.QueryString["id"];
if(int.TryParse(str_id,out id))
{
//id now contains your int value
}
else
{
//str_id contained something else, i.e. not int
}
replace with this one
string str_id;
str_id = Request.QueryString["id"];
int id = Convert.ToInt32(str_id);
or simply and more efficient one
string str_id;
str_id = Request.QueryString["id"];
int id = int.Parse(str_id);
int id = Convert.ToInt32(str_id, CultureInfo.InvariantCulture);
There are several ways you can do that
string str_id = Request.QueryString["id"];
int id = 0;
//this prevent exception being thrown in case query string value is not a valid integer
Int32.TryParse(str_id, out id); //returns true if str_id is a valid integer and set the value of id to the value. False otherwise and id remains zero
Others
int id = Int32.Parse(str_id); //will throw exception if string is not valid integer
int id = Convert.ToInt32(str_id); //will throw exception if string is not valid integer
you have to use int.Parse(str_id)
Edit : don't trust user input
it's better to check if the input is a number or not before parsing , for this use int.TryParse

Convert string value back to GUID value

i have a guid value that i store in my hidden variable.
say for eg (303427ca-2a5c-df11-a391-005056b73dd7)
now how do i convert the value from this hidden field back to GUID value (because the method i would be calling expects a GUID value).
thank you.
Just use the overloaded constructor:
try
{
Guid guid = new Guid("{D843D80B-F77D-4655-8A3E-684CC35B26CB}");
}
catch (Exception ex) // There might be a more appropriate exception to catch
{
// Do something here in case the parsing fails.
}
You are making it pretty easy on an attacker by storing the Guid in a string. Trivial to find back in, say, the paging file. Store it in a Guid and kill two birds with one stone.
string strGuid;
strGuid = (your guid here);
Guid guid = new Guid(strGuid);
For more info, MSDN
Guid has a constructor for string Guids.
Guid guid = new Guid(myStringGuid);
new Guid(myHiddenFieldString)
I think it can be done simply as following:
Guid MyGuid = new Guid(stringValue);
In .NET4 onwards you can also use:
Guid myGuid = Guid.Parse(myGuidString);
Just a matter of coding preference, but some people find this more intuitive.

Categories