Question

In VB.NET, I want to simulate a way to "force" the ASC function to use the english codepage, even on a system having the "language for non-unicode" different than English.

For example:

Asc("Œ")

On a system having "language for non-unicode" set as English, currently the result is 140

On a system having "language for non-unicode" set as Slovakian, currently the result is 79

The twist is I CANNOT user AscW (for reasons I cannot disclose)

In the particular example above I would need for the code to always return 140.


If there's a way to force the whole program to use the english code page I could work with that as well.

I've tried playing with the CurrentCulture:

Threading.Thread.CurrentThread.CurrentCulture = New Globalization.CultureInfo("en-US")
Threading.Thread.CurrentThread.CurrentUICulture = New Globalization.CultureInfo("en-US")

Right before Asc or even as the first line on the ApplicationEvent's Startup, but no luck.

Thanks!

Was it helpful?

Solution

From using ILSpy, it looks like Asc uses Encoding.Default to get the default encoding for the os to determine how to get the bytes. So you will have to roll your own:

    Dim enc As System.Text.Encoding = System.Text.Encoding.GetEncoding(1252)   '1252 is the default codepage on US Windows
    Dim arr() As Byte = enc.GetBytes("Œ")
    MessageBox.Show(arr(0))

OTHER TIPS

I'm not sure how to control the code page used by ASC, so this doesn't directly answer your question, but I would suggest, rather, that you use the Encoding class to perform your ASCII encoding and decoding. The Asc method is primarily there for backwards compatibility with VB6 code. For instance, to get the ASCII values using the old IBM English code page (437), you could do this:

Public Function EnglishAsc(ByVal Text As String) As Byte
    Dim enc As Encoding = Encoding.GetEncoding(437)
    Dim bytes As Byte() = enc.GetBytes(Text)
    If bytes.Length > 0 Then
        Return bytes(0)
    Else
        Return 0
    End If
End Function

Public Function EnglishAsc(ByVal Character As Char) As Byte
    Dim enc As Encoding = Encoding.GetEncoding(437)
    Dim bytes As Byte() = enc.GetBytes(New Char() {Character})
    If bytes.Length > 0 Then
        Return bytes(0)
    Else
        Return 0
    End If
End Function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top