C#铸造的MemoryStream对FILESTREAM [英] C# Casting MemoryStream to FileStream

查看:532
本文介绍了C#铸造的MemoryStream对FILESTREAM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码是这样的:

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



后来我用file.Name。

Later I'm using file.Name.

我收到一个InvalidCastException:它会显示如下

I'm getting an InvalidCastException: it displays follows

无法转换类型'System.IO.MemoryStream对象键入System.IO.FileStream。

Unable to cast object of type 'System.IO.MemoryStream' to type 'System.IO.FileStream'.

我读的地方,我应该只是改变的FileStream到流。有没有别的东西我应该怎么办?

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

推荐答案

A 的MemoryStream 未与文件相关联,并且没有一个文件名的概念。基本上,你不能这样做,

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

您可以施放一个的MemoryStream 平凡,和的MemoryStream 通过类型检查;但从来没有一个的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.

您的可以子类的MemoryStream 并添加名称属性(您提供一个值),但仍然没有共同性之间的的FileStream YourCustomMemoryStream 的FileStream 没有按' ŧ实施预先存在的界面获得名称;所以调用者就必须为明确分别处理两种,或者使用鸭打字(通过动态或反射可能)。

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).

另一种选择(也许更容易)可能是:将数据写入到一个临时文件;使用的FileStream 从那里;然后(后下)删除的文件。

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

这篇关于C#铸造的MemoryStream对FILESTREAM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆