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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With