Reputation: 47
I want to check the encoding in a string with C#.
Is there any possible way?
I was trying with StreamReader but I don't have path.
foreach (string um in userMasterList)
{
counter++;
TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
string finalName = null;
if (!string.IsNullOrEmpty(um))
{
//string str = StreamReader.CurrentEncoding.ToString();
string Name = um.Trim();
//StreamReader sr = new StreamReader(Name);
// MessageBox.Show(sr.CurrentEncoding.ToString());
if (!Regex.IsMatch(Name, "^[a-zA-Z0-9]*$"))
{
finalName = GreekToLower(Name);
finalName = textInfo.ToTitleCase(finalName);
}
else
{
finalName = textInfo.ToTitleCase(Name.ToLower());
}
finalList.Add(finalName);
}
else
{
finalList.Add("-");
}
}
Upvotes: 1
Views: 3429
Reputation: 1522
My Code:
public static bool IsOnlyUTF8(string value)
{
byte[] bytes = value.ToCharArray()
.Select(c => (byte)c)
.ToArray();
string decodedString = System.Text.Encoding.UTF8.GetString(bytes);
return value.Equals(decodedString);
}
Upvotes: 1
Reputation: 91
Not sure whether this will answer your question:
public static bool CheckEncoding(string value, Encoding encoding)
{
bool retCode;
var charArray = value.ToCharArray();
byte[] bytes = new byte[charArray.Length];
for (int i = 0; i < charArray.Length; i++)
{
bytes[i] = (byte)charArray[i];
}
retCode = string.Equals(encoding.GetString(bytes, 0, bytes.Length), value, StringComparison.InvariantCulture);
return retCode;
}
Calling Code:
CheckEncoding("Prüfung", Encoding.ASCII); //false
Upvotes: 4