Skip to content

How to add arraylist items to a unique stream

Diogo

Asked Apr 24, 2008, 6:52 AM EDT2 answers
Share
LinkedInX
Hi folks!

Well, take a look:
int nfiles = arrArchives.Count;
Stream st = null;
for (int i = 0; i <= nfiles; i++)
{
    st = arrArchives[i];
}


So, I want add arraylist items into "st" stream, how to do this?
This below code don´t works, the error: "Cannot convert source type 'object' to target type 'System.IO.Stream'"

Thanks in advanced :)

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    If the arrArchives array contained Stream objects this would work. Are you missing a cast? What are you attempting to store in the ArrayList? If you are storing Stream objects in the array list, you can simply assign them back the stream with a cast:

    int nfiles = arrArchives.Count;
    Stream st = null;
    for (int i = 0; i <= nfiles; i++)
    {
        st = (Stream)arrArchives[i];
    }

    Althought its seems kind of redundant, lol.

    However, if the objects you are storing in the arraylist arent of type Stream or derive from Stream, you will get an InvalidCastException.

    If your just trying to write to the stream, you will need to initalize the stream before you can write to it. If you just want to store the data, you can use a MemoryStream, something like this:

    int nfiles = arrArchives.Count;
    Stream st = new MemoryStream();
    for (int i = 0; i <= nfiles; i++)
    {
        //This will cause a compile error though...
        st.Write(arrArchives[i]);
    }

    But we need to know what your storing in the ArrayList collection before we can get any further :)
    0
  • 0
    Also, this is a good time to introduce you to generics. Instead of using an ArrayList, you could do something like this:

    List<Stream> arrArchives = new List<Stream>();

    This will create a generic collection much like the ArrayList, except no casting is involved. So instead of storing objects in the collection, your storing Stream objects, which makes it much more typesafe because when you use the collection, you will already know whats stored in it and wont have to backtrack or remember.
    0