C# Casting MemoryStream to FileStream

烂漫一生 提交于 2019-12-09 17:54:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!