问题
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?
回答1:
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.
回答2:
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.
回答3:
This operation is not possible. Both FileStream
and MemoryStream
are directly derived from Stream
, so they are sibling types. In general, in the following scenario:
public class A { }
public class B : A { }
public class C : A { }
It is not possible to cast B to C or vice-versa. There is no "is-a" relationship between B and C.
来源:https://stackoverflow.com/questions/8297613/c-sharp-casting-memorystream-to-filestream