There have been many postings about this subject on this newsgroup.
Unfortunately, they're incorrect. You can't just cast a value in C#
and have it work for all ASCII characters. Nor can you use the ASCII
encoding as some have suggested.
The undocumented truth is, Microsoft uses the Western European encoding
in these functions. If you don't believe me, use 137 in your VB Chr
function then compare the C# output if you just cast it or use the
ASCII encoding. You'll see they don't match! You can even do a quick
loop and check all the values from 0 to 255 and you'll see that there
are many that won't match the VB function's output.
Now if you're doing simple stuff, that maybe OK but if your writing
components in one language and expect to communicate with components
written in the other, you're going to have a real problem. Case in
point, you've got an older VB6 object (or VB.Net object for that
matter) that uses it's own encryption algorithm and it must communicate
with a C# object that must mimic the encryption function. If you don't
use the proper implementation of the Chr and Asc functions in your C#
component, you'll never be able to decipher the encrypted data from the
VB component.
Here are the true implementations of the Asc and Chr functions:
internal static string Chr(int p_intByte)
{
if( (p_intByte < 0) || (p_intByte > 255) )
{
throw new ArgumentOutOfRa ngeException("p _intByte", p_intByte,
"Must be between 0 and 255.");
}
byte[] bytBuffer = new byte[]{(byte) p_intByte};
return Encoding.GetEnc oding(1252).Get String(bytBuffe r);
}
internal static int Asc(string p_strChar)
{
if( p_strChar.Lengt h != 1 )
{
throw new ArgumentOutOfRa ngeException("p _strChar", p_strChar,
"Must be a single character.");
}
char[] chrBuffer = {Convert.ToChar (p_strChar)};
byte[] bytBuffer = Encoding.GetEnc oding(1252).Get Bytes(chrBuffer );
return (int) bytBuffer[0];
}
I hope this answers the question once and for all and puts an end to
the huge amount of misinformation that exists out there on this
subject.
Darrell Sparti, MCSD
Bikers Against Child Abuse National Webmaster
we*******@bacau sa.com
www.bacausa.com
Because No Child Should Live In Fear