简体   繁体   中英

Does not contain definition for ASCII

So I'm trying to use a bluetooth module (HC-06) to read data sent to my Netduino board from my cell phone. However, I cant get the bytes converted into text so I can compare the characters I send and thus turn them into conditional statements. From what I've seen I need to use the following line of code in C# to change it from a byte array to a string, however I cannot find a definition for class in my scope!! Here is the line:

Encoding.ASCII.GetString();

And here is the error I'm getting:

'System.Text.Encoding' does not contain definition for 'ASCII'

I'm using the .Net Micro Framework version 4.1 with the Visual Studio Express 2012 IDE. I'm using the original Netduino , Netduino 1 with the 4.1 Framework .

ASCII encoding isn't included because it is not necessary. UTF-8 is the same as ASCII, the MSB is irrelevant in text streams. You should be able to get a correct textual representation using the UTF8 encoding, as long as the content was sent and received properly. For example, if buffer contains your received text...

Debug.Print(new String(Encoding.UTF8.GetChars(buffer, 0, buffer.Length)));

Encoding.ASCII exists in the .NET 4.7.2 standard, but not everywhere. See

https://docs.microsoft.com/en-us/dotnet/api/system.text.encoding.ascii?view=netframework-4.7.2

If, like me, you stumbled across this page because you are developing a portable library, you will notice toward the bottom of that page in the Applies To section that Encoding.ASCII is not available in all contexts.

Anywhere 7 bit encoding is not available, you will need to filter out any bytes that are 8 bit and above by hand and use Encoding.UTF8. An easy way to do this uses Regex replace. You can modify the below code if you are ok with allowing nulls inside your string, I exclude them.

String MyASCIIString = Encoding.UTF8.GetString(MyByteArray);
Regex NotASCII = new Regex("[^\u0001-\u007f]+");
MyASCIIString = NotASCII.Replace(MyASCIIString, "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM