转 FileStream Read File
2014-04-22 14:27
363 查看
FileStream Read File [C#]
This example shows how to safely read file using FileStream in C#. To be sure the whole file is correctly read, you should call FileStream.Read method in a loop, even if in the most cases the whole file is read in a single call of FileStream.Read method.
Read file using FileStream
First create FileStream to open a file for reading. Then call FileStream.Read in a loop until the whole file is read. Finally close the stream.
[C#]
This example shows how to safely read file using FileStream in C#. To be sure the whole file is correctly read, you should call FileStream.Read method in a loop, even if in the most cases the whole file is read in a single call of FileStream.Read method.
Read file using FileStream
First create FileStream to open a file for reading. Then call FileStream.Read in a loop until the whole file is read. Finally close the stream.
[C#]
using System.IO; public static byte[] ReadFile(string filePath) { byte[] buffer; FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); try { int length = (int)fileStream.Length; // get file length buffer = new byte[length]; // create buffer int count; // actual number of bytes read int sum = 0; // total number of bytes read // read until Read method returns 0 (end of the stream has been reached) while ((count = fileStream.Read(buffer, sum, length - sum)) > 0) sum += count; // sum is a buffer offset for next reading } finally { fileStream.Close(); } return buffer; }
相关文章推荐
- 计算彩色的BGR图像的直方图
- 编程杂项
- 小盆友 为什么你总是做不好营销?
- 10个核心的Linux面试问题与答案
- MongoDb 结果漂亮点!
- [Android学习笔记]Bitmap,BitmapDrawable,BitmapFactory学习笔记
- filestream read方法 循环读取固定文件
- /sys 下的目录结构
- android学习笔记---fragment适配手机和平板
- Cassandra与HBase的大数据对决 谁是胜者?
- 第九周-项目一运算符重载
- msi
- Android中的ID能否重名
- 关于指针数组和数组指针的浅谈
- activemq报EOFExceptionjvm错误
- wxPython 2.6.2.1在 redhat上 安装
- 阿里巴巴面试过程及总结
- 先进的微软视窗软件保护系统WinLicense
- android数据库拷贝出错
- Android多屏滑动:ViewPager基础使用及PagerTabStrip先天缺陷(附源码)