Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Casting MemoryStream to FileStream

My code is this:

byte[] byteArray = Encoding.ASCII.GetBytes(someText);
MemoryStream stream = new MemoryStream(byteArray);
StreamReader reader = new StreamReader(stream);
FileStream file = (FileStream)reader.BaseStream;

Later I'm using file.Name.

I'm getting an InvalidCastException: it displays follows

Unable to cast object of type 'System.IO.MemoryStream' to type 'System.IO.FileStream'.

I read somewhere that I should just change FileStream to Stream. Is there something else I should do?

like image 437
petko_stankoski Avatar asked Nov 28 '11 14:11

petko_stankoski


2 Answers

A MemoryStream is not associated with a file, and has no concept of a filename. Basically, you can't do that.

You certainly can't cast between them; you can only cast upwards an downwards - not sideways; to visualise:

        Stream
          |
   ---------------
   |             |
FileStream    MemoryStream

You can cast a MemoryStream to a Stream trivially, and a Stream to a MemoryStream via a type-check; but never a FileStream to a MemoryStream. That is like saying a dog is an animal, and an elephant is an animal, so we can cast a dog to an elephant.

You could subclass MemoryStream and add a Name property (that you supply a value for), but there would still be no commonality between a FileStream and a YourCustomMemoryStream, and FileStream doesn't implement a pre-existing interface to get a Name; so the caller would have to explicitly handle both separately, or use duck-typing (maybe via dynamic or reflection).

Another option (perhaps easier) might be: write your data to a temporary file; use a FileStream from there; then (later) delete the file.

like image 125
Marc Gravell Avatar answered Sep 22 '22 18:09

Marc Gravell


You can compare Stream with animal, MemoryStream with dog and FileStream with cat. Although a dog is an animal, and a cat is an animal, a dog certainly is not a cat.

If you want to copy data from one stream to another, you will need to create both streams, read from one and write to the other.

like image 41
C.Evenhuis Avatar answered Sep 20 '22 18:09

C.Evenhuis