ArrayList to bytes

N

Neil Cowburn

when a try run your code ( byte[] array = (byte[])list.ToArray(typeof
(Byte));) its give me a InvalidCastException.

The InvalidCastException tells me that the ArrayList, list, contains
types that are not of type Byte.

If you want to convert an ArrayList that's populated like this:

ArrayList list = new ArrayList();
list.Add("one");
list.Add(2);
list.Add(true);

then you need to enumerate each element in the ArrayList and manually
convert to bytes.
 
A

Armando Rocha

Hi,

my arraylist collect string types.

I read lines from a text file, and i add to arraylist each line:

TextReader sr = new StreamReader(PATH+ @"\LOG.txt");
String sLine = "";
aList = new ArrayList();

while ((sLine = sr.ReadLine()) != null)
{
if (Count > 0)
{
//### ARRAYLIST ####
aList.Add(sLine);
}
Count++;
}
sr.Close();

//After i want convert my ArrayList (aList) to byte array like you tould;
if (aList.Count > 0)
byte[] array = (byte[])aList.ToArray(typeof(string));

but its give me a InvalidCastException.

I hope that sample above helps you to help me... :)


--
Armando Rocha
Mobile Developer

http://www.ifthensoftware.com
PORTUGAL
Neil Cowburn said:
when a try run your code ( byte[] array = (byte[])list.ToArray(typeof
(Byte));) its give me a InvalidCastException.

The InvalidCastException tells me that the ArrayList, list, contains types
that are not of type Byte.

If you want to convert an ArrayList that's populated like this:

ArrayList list = new ArrayList();
list.Add("one");
list.Add(2);
list.Add(true);

then you need to enumerate each element in the ArrayList and manually
convert to bytes.
 
N

Neil Cowburn

Hi,

my arraylist collect string types.

I read lines from a text file, and i add to arraylist each line:

TextReader sr = new StreamReader(PATH+ @"\LOG.txt");
String sLine = "";
aList = new ArrayList();

while ((sLine = sr.ReadLine()) != null)
{
if (Count > 0)
{
//### ARRAYLIST ####
aList.Add(sLine);
}
Count++;
}
sr.Close();

//After i want convert my ArrayList (aList) to byte array like you tould;
if (aList.Count > 0)
byte[] array = (byte[])aList.ToArray(typeof(string));

but its give me a InvalidCastException.

I hope that sample above helps you to help me... :)

If all you want to do is read a file to a byte array, then why not use
FileStream instead of StreamReader?

byte[] buffer;
using(FileStream fs = File.OpenText(Path.Combine(PATH, "Log.txt")))
{
buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
}
 

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

Similar Threads

Downgrade to CF 2.0 2
Size in Bytes transfered... 3
Threads help 9
Restart Application 8
String Format Custom 8
Call WebService on Device application 6
ArrayList Remove Item 2
Add Enum to Arraylist 1

Top