ArrayList Of Bytes to Byte Array?

How can I convert an ArrayList of Bytes to a Byte Array?

This would be in C#.

Any help would be greatly appreciated.

Thanks
LVL 1
davismAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Fareed Ali KhanCommented:
use the following:

            ArrayList arr = new ArrayList();
            byte[] barr = (byte[])arr.ToArray(typeof(byte));
Fareed Ali KhanCommented:
See the following URL if you want more details:

https://msdn.microsoft.com/en-us/library/fcyyh2hb(v=vs.110).aspx
Fernando SotoRetiredCommented:
Try this.

byte[] myByteArray = ArrayListofBytes.Cast<byte>(). ToArray();
PMI ACP® Project Management

Prepare for the PMI Agile Certified Practitioner (PMI-ACP)® exam, which formally recognizes your knowledge of agile principles and your skill with agile techniques.

davismAuthor Commented:
I was somewhat thinking a lot those lines too but when I tried even your code I get:

"At least one element in the source array could not be cast down to the destination array type."

Is that trying to say at least one element in the source array is not a byte list item? Because that's not the case and I would've gotten an error on creating it.
Mike TomlinsonHigh School Computer Science, Computer Applications, and Mathematics TeachersCommented:
Yes...one of the elements doesn't fall in the range for byte: 0 - 255
Fernando SotoRetiredCommented:
Hi davism;

A byte is an Unsigned 8-bit integer which has the valid values from 0 to 255 as stated in the Microsoft documentation.. So one of the values must be outside that range.
it_saigeDeveloperCommented:
Because that's not the case and I would've gotten an error on creating it.
This is not a true statement.  An ArrayList is equivalent (essentially) to a List<object>.  Other than guaranteeing object, an ArrayList is not type safe; Proof of Concept -
using System;
using System.Collections;

namespace EE_Q28692546
{
	class Program
	{
		static void Main(string[] args)
		{
			ArrayList arr = new ArrayList();
			arr.Add("Hello World");
			arr.Add(1);
			arr.Add(new byte[] { 0 });
			arr.Add(new Customer() { ID = 1, Name = "Jim" });

			foreach (var item in arr)
				Console.WriteLine(item);
			Console.ReadLine();
		}
	}

	class Customer
	{
		public int ID { get; set; }
		public string Name { get; set; }

		public override string ToString()
		{
			return string.Format("{0} [{1}]", Name, ID);
		}
	}
}

Open in new window

Produces the following output -Capture.JPGIf you want to guarantee type, use a List<T> -or- List(Of T).  In your case this would be a List<byte> [C#] or List(Of Byte) [VB.NET].

-saige-
davismAuthor Commented:
The ArrayList was created from a MemoryStream.ToArray.

Would that have an impact?

Is that a way to convert the Arraylist it generated back to a MemoryStream?
Fernando SotoRetiredCommented:
An ArrayList holds a collection of objects, not of any specific type. So to your question, "Would that have an impact?", that depends on what type of objects the MemoryStream was using, if they were all Bytes then no if it was anything else then yes.
Mike TomlinsonHigh School Computer Science, Computer Applications, and Mathematics TeachersCommented:
MemoryStream.ToArray() itself wouldn't generate anything outside the normal range for a byte array....but it's possible for the ArrayList to hold other things in it besides bytes.  Did you add anything to the ArrayList manually?  Show us the code that generates the ArrayList?...and why ArrayList instead of a byte array?
davismAuthor Commented:
MemoryStream pMS = new MemoryStream();
img.Save(pMS, iInfo, eParams);

Open in new window


I am so with you. I would have done a bytearray but is it what it is and I didn't write this. Just using the results.

Just so you are aware this is a TIFF image. The iInfo is the codec, the eParams is the Encoder for the CCITT4 (basically a fax).
Mike TomlinsonHigh School Computer Science, Computer Applications, and Mathematics TeachersCommented:
So where is the ArrayList being created and 'pMS.ToArray()' being called?
davismAuthor Commented:
ArrayList is being created above that line in the same function with a

ArrayList Result = new ArrayList();

Ooopppssss and sorry right below the line on the Save is the:

Result.Add(pMS.ToArray());

I thought I put that in there. My bad.

I think I might have a direction with this.

I am serializing it and putting it back into a memorystream.

I am going to recreate the TIFF images out of that. At least I hope anyway.
davismAuthor Commented:
Or more so save the file in the appropriate context at the time of creating the memorystream and save it to a bytearray.

It seems a little awkward that one can create an populate an arraylist from a memorystream yet not reverse it to take the same bytes in the ArrayList and create the MemoryStream.

That just seems a little strange.
Mike TomlinsonHigh School Computer Science, Computer Applications, and Mathematics TeachersCommented:
Still don't see why ArrayList though...
davismAuthor Commented:
Yeah, why an ArrayList was done instead of a Byte array is beyond me. I wasn't involved at the time. Just working with was done.

I'm going to a few more testing aspects but I thing I've taken a different approach.

However, I am still interested in how I can take an created and populated ArrayList that was from a MemoryStream and convert it back to a MemoryStream.

Any thoughts or ideas on that? Anybody? I know I took an alternative approach but that doesn't answer the main item or OP question.
Mike TomlinsonHigh School Computer Science, Computer Applications, and Mathematics TeachersCommented:
You convert it to a byte array and then pass that to the constructor of MemoryStream:
https://msdn.microsoft.com/en-us/library/e55f3s5k(v=vs.110).aspx
it_saigeDeveloperCommented:
There appears to be a disconnect happening here.

The code that you have shown thus far, illustrates that you are adding a byte array to an arraylist, not creating an arraylist from a memory stream.  Natively, .NET does not contain a method that creates/converts a MemoryStream into an array list.  .NET does, however, natively contain a method that will create/convert a MemoryStream into a byte array.Capture.JPGThat being said, what you would do in order to revert the byte array element(s) of your array list back into memory stream objects is match the type and create a memory stream from a byte array using the memory stream's overloaded constructor.  For example:
using System;
using System.Collections;
using System.IO;

namespace EE_Q28692546
{
	class Program
	{
		static void Main(string[] args)
		{
			ArrayList arr = new ArrayList();
			arr.Add("Hello World");
			arr.Add(1);
			arr.Add(new byte());
			arr.Add(new Customer() { ID = 1, Name = "Jim" });

			using (MemoryStream ms = new MemoryStream())
				arr.Add(ms.ToArray());

			foreach (var item in arr)
				Console.WriteLine("{0} is a {1} type", item, item.GetType());

			var reverted = default(MemoryStream);
			foreach (var item in arr)
			{
				if (item.GetType() == typeof(byte[]))
				{
					reverted = new MemoryStream(item as byte[]);
					break;
				}
			}

			if (reverted != default(MemoryStream))
				Console.WriteLine("Generated the memory stream from the byte array in the array list");
			else
				Console.WriteLine("Array list did not contain a byte array");

			Console.ReadLine();
		}
	}

	class Customer
	{
		public int ID { get; set; }
		public string Name { get; set; }

		public override string ToString()
		{
			return string.Format("{0} [{1}]", Name, ID);
		}
	}
}

Open in new window

Produces the following output -Capture.JPG-saige-
davismAuthor Commented:

The code that you have shown thus far, illustrates that you are adding a byte array to an arraylist, not creating an arraylist from a memory stream.  Natively, .NET does not contain a method that creates/converts a MemoryStream into an array list.  .NET does, however, natively contain a method that will create/convert a MemoryStream into a byte array.

The "Result.Add(pMS.ToArray());" where Results is clearly from an arraylist by way of "ArrayList Result = new ArrayList();"

In a sense you are correct in that I am not creating it directly from the memorysteam. The MemoryStream is creating the ByteArray and that byte array is being added to the ArrayList.

However, I am going to explore more of what you identified here.

Let me explorer that today.
Mike TomlinsonHigh School Computer Science, Computer Applications, and Mathematics TeachersCommented:
If that ArrayList isn't being used for anything else other than the image bytes then switch to a List<byte>:
// ...
List<byte> Result = new List<byte>(pMS.ToArray());
// ...
MemoryStream newMS = new MemoryStream(Result.ToArray());

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
davismAuthor Commented:
Yes, it would make sense to just switch it but unfortunately, I cannot make that call. I am not sure who else or what else is using it.  I did an overload and have it returns the byte array instead.

Thanks for the information! Greatly appreciated!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.