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
MemoryStreamis 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:
You can cast a
MemoryStreamto aStreamtrivially, and aStreamto aMemoryStreamvia a type-check; but never aFileStreamto aMemoryStream. 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
MemoryStreamand add aNameproperty (that you supply a value for), but there would still be no commonality between aFileStreamand aYourCustomMemoryStream, andFileStreamdoesn’t implement a pre-existing interface to get aName; so the caller would have to explicitly handle both separately, or use duck-typing (maybe viadynamicor reflection).Another option (perhaps easier) might be: write your data to a temporary file; use a
FileStreamfrom there; then (later) delete the file.