问题
I am facing a strange problem that my service would not return any results, if I search for a product name (eg: ABC 123 XYZ) by pasting the string in to the search text box in my winform app.
The user follows this mode and faces the problem to search: A table with product names in outlook - copied in to excel - and then a string from that table in excel is copied in to my application's search text box to search.
The same string when I type it in manually(ABC 123 XYZ) in to my search box, works fine and service returns the result. Hence I suspected some encoding issue when the value is copied from excel in to my app's text box.
I did some reading on encoding and found this tool. http://www.codeproject.com/Articles/17201/Detect-Encoding-for-In-and-Outgoing-Text
When I copy the text from excel - it shows 'Western European(Windows), iso-8859-1.
When I type it in - it shows US-ASCII. So, I concluded that it is better to convert my text to US-ASCII always.
Text encoding when typed in to text box directly
Text encoding when I copied from an excel cell
I followed the below code to convert it to US-ASCII and find this to work. The problem seems to be in the 'space' between the letters and hence in the below code, the EncoderReplacementFallback is " ".
string inputString = textBox1.Text;
Encoding encoder = ASCIIEncoding.GetEncoding("us-ascii",
new EncoderReplacementFallback(" "),
new DecoderExceptionFallback());
byte[] bAsciiString = encoder.GetBytes(inputString);
string cleanString = new ASCIIEncoding().GetString(bAsciiString);
This code makes it work though.
I am not sure if this approach is right to convert any string pasted or typed in to the search box. Will this work for all cases irrespective of what encoding the pasted text is or when typing by hands ?
Thanks.
来源:https://stackoverflow.com/questions/12840027/string-encoding-issue-need-to-convert-western-european-to-ascii