C # Casting a MemoryStream to a FileStream

My code is:

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

Later I use file.Name.

I get an InvalidCastException: it displays the following

Cannot overlay an object of type "System.IO.MemoryStream" with type "System.IO.FileStream".

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

+6
source share
3 answers

A MemoryStream not associated with a file and has no concept of a file name. In principle, you cannot do this.

You cannot throw between them; you can only throw up and down - not sideways; for visualization:

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

You can make a MemoryStream to Stream trivial and Stream to MemoryStream using type checking; but never FileStream until MemoryStream . It is like a dog is an animal and an elephant is an animal, so we can throw the dog to an elephant.

You can subclass MemoryStream and add the Name property (which you specify), but there will be no commonality between FileStream and a YourCustomMemoryStream , and FileStream will not implement the existing interface to get Name ; therefore, the caller will have to explicitly process both separately and use duck print (possibly through dynamic or reflection).

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

+16
source

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

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

+4
source

This operation is not possible. Both FileStream and MemoryStream made directly from Stream , so they are related types. In general, in the following scenario:

  public class A { } public class B : A { } public class C : A { } 

It is impossible to distinguish B from C or vice versa. There is no "is-a" relationship between B and C.

+3
source

Source: https://habr.com/ru/post/902565/


All Articles