zoukankan      html  css  js  c++  java
  • 转 FileStream Read File

    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#]

     1 using System.IO;
     2 public static byte[] ReadFile(string filePath)
     3 {
     4   byte[] buffer;
     5   FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
     6   try
     7   {
     8     int length = (int)fileStream.Length;  // get file length
     9     buffer = new byte[length];            // create buffer
    10     int count;                            // actual number of bytes read
    11     int sum = 0;                          // total number of bytes read
    12 
    13 
    14     // read until Read method returns 0 (end of the stream has been reached)
    15     while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
    16       sum += count;  // sum is a buffer offset for next reading
    17   }
    18   finally
    19   {
    20     fileStream.Close();
    21   }
    22   return buffer;
    23 }
  • 相关阅读:
    TCP流量控制
    TCP可靠传输的实现
    springbean补充:关于bean的属性
    mybatis分页插件,自动生成代码插件
    mybatis拦截器,分页插件
    mybatis注解开发
    mybatis缓存
    mybatis调用存储过程
    Oracle学习笔记12:oracle优化
    Oracle学习笔记11:触发器
  • 原文地址:https://www.cnblogs.com/frustrate2/p/3680474.html
Copyright © 2011-2022 走看看