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)
Related
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.
This question already has answers here:
Convert a string to an enum in C#
(29 answers)
How to get enum value by string or int
(13 answers)
Closed 1 year ago.
When I say Key, I'm referring to the "Keys" enum in Windows Forms. For instance:
I might have a string:
string key = "Q";
And I'm trying to convert it to this:
Keys.Q
How would I do this? (If even possible)
In case that the values of the string are not exactly the same as the enum you can do it with a switch-case statment.
Keys keys = key switch
{
"Q" => Keys.Q
...
};
If the values exactly the same just parse it:
public static TEnum ToEnum<TEnum>(this string strEnumValue)
{
if (!Enum.IsDefined(typeof(TEnum), strEnumValue))
{
throw new Exception("Enum can't be parsed");
}
return (TEnum)Enum.Parse(typeof(TEnum), strEnumValue);
}
Keys keys = key.ToEnum<Keys>();
This question already has answers here:
Get URL parameters from a string in .NET
(17 answers)
Closed 5 years ago.
I have a string which basically looks like this:
/giveaway/host/setup/ref=aga_h_su_dp?_encoding=UTF8&value_id=1484778065
The trick here is that the length of the string can vary and will change... However the part with "value_id=something" always stays same... So the problem that I ran in was that I can do something like this:
var myId = string.SubString(30,45);
to get the value after value_id= /*this one here*/
I'm thinking that this can be solved by regex or some other way, but I'm not too sure how to write such one. Can someone help me out?
Could you try this. If your value_id always the last of your string you can use this.
var str = "/giveaway/host/setup/ref=aga_h_su_dp?_encoding=UTF8&value_id=1484778065";
var valueId = str.Split('=').LastOrDefault();
Result : 1484778065
Hope it's help to you
You can split by 'value_id='
string[] tokens = str.Split(new[] { "value_id=" }, StringSplitOptions.None);
if(tokens.Length>1){
//parse tokens[1] with the value
}
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);
}
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)