缓存在C#中的二进制文件 [英] Caching a binary file in C#

查看:132
本文介绍了缓存在C#中的二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以缓存在.NET中的二进制文件和缓存的文件做正常的文件操作?

Is it possible to cache a binary file in .NET and do normal file operations on cached file?

推荐答案

的方式要做到这一点是从阅读全部内容的FileStream 的MemoryStream 对象,然后使用这个对象,因为我/ O以后。这两种类型,从继承,所以使用量将得到有效相同

The way to do this is to read the entire contents from the FileStream into a MemoryStream object, and then use this object for I/O later on. Both types inherit from Stream, so the usage will be effectively identical.

下面是一个例子:

private MemoryStream cachedStream;

public void CacheFile(string fileName)
{
    cachedStream = new MemoryStream(File.ReadAllBytes(fileName));
}



所以才称之为求CacheFile 方法一次,当你希望缓存指定的文件,然后其他地方在代码中使用 cachedStream 阅读。 (实际文件将被尽快的内容被缓存关闭)。只有要记住的事情是处置 cachedStream 当你完成它。

So just call the CacheFile method once when you want to cache the given file, and then anywhere else in code use cachedStream for reading. (The actual file will been closed as soon as its contents was cached.) Only thing to remember is to dispose cachedStream when you're finished with it.

这篇关于缓存在C#中的二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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