char[] to byte[]

P

Petar Popara

I have this case:

int bufferLen = Convert.ToInt32(file.Length);
char[] buffer = new char[bufferLen];
int len = sr.Read(buffer, 0, bufferLen);
rawBytes.setBytesArray(buffer);

While executing above code I got this (COM, automation) error at last line:

An unhandled exception of type
'System.Runtime.InteropServices.SafeArrayTypeMismatchException' occurred in
MyApp.exe

That is because buffer have to be of byte[] type and not char[]. But, if I
change "buffer" to byte[] than I got compiler error saying that sr.Read() is
expecting char[] instead of byte[]. :(

What should I do? Cast? How? Something like this:

int len = sr.Read((char[])buffer, 0, bufferLen);
 
G

Guest

If you need to do some quick and easy conversion of arrays between char[] and
byte[], take a look at the GetBytes() and GetChars() methods contained within
System.Text.Encoding.<Desired Encoding>.

Brendan
 
J

Jay B. Harlow [MVP - Outlook]

Petar,
In addition to System.Text.Encoding, you might be able to use
System.Buffer.BlockCopy if you don't want any encoding changes at all.

Also instead of using a StreamReader, which is for Text encoded files, you
should consider simply use Stream.

Something like:

Stream stream = New FileStream(...);

| int bufferLen = Convert.ToInt32(file.Length);
| byte[] buffer = new byte[bufferLen];
int len = stream.Read(buffer, 0, bufferLen);
| rawBytes.setBytesArray(buffer);

Hope this helps
Jay

|
| I have this case:
|
| int bufferLen = Convert.ToInt32(file.Length);
| char[] buffer = new char[bufferLen];
| int len = sr.Read(buffer, 0, bufferLen);
| rawBytes.setBytesArray(buffer);
|
| While executing above code I got this (COM, automation) error at last
line:
|
| An unhandled exception of type
| 'System.Runtime.InteropServices.SafeArrayTypeMismatchException' occurred
in
| MyApp.exe
|
| That is because buffer have to be of byte[] type and not char[]. But, if I
| change "buffer" to byte[] than I got compiler error saying that sr.Read()
is
| expecting char[] instead of byte[]. :(
|
| What should I do? Cast? How? Something like this:
|
| int len = sr.Read((char[])buffer, 0, bufferLen);
|
|
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top