zoukankan      html  css  js  c++  java
  • 初识IO流——二进制文件的读和写操作

      C#中,二进制文件的写和读操作分别由BinaryWrite类和BinaryReader类实现,它们都所属与System.IO命名空间。

      BinaryWriter类以二进制的形式将基元写入流,并支持用特定的编码写入字符串。

      BinaryReader类用特定的编码将基元数据类型读作二进制值。

      根据BinaryWriter类和BinaryReader类的实现写和读过程,其实可以将二者理解为一个"互逆"的过程。

      示例:分别用BinaryWrite类和BinaryReader类实现二进制文件的写操作和读操作。

      (1)BinaryWrite类实现写入操作:

     1 public void DoWrite(string str)
     2         {
     3             /*文件在项目中的相对于根目录的位置*/
     4             string Relative_path = "/Binary/first_" + DateTime.Today.ToString("yy-MM-dd") + ".dat";
     5 
     6             /*获取项目的根目录*/
     7             string Full_path = AppDomain.CurrentDomain.BaseDirectory + Relative_path;
     8 
     9             FileStream filestream = new FileStream(Full_path, FileMode.Append, FileAccess.Write);
    10 
    11             using (BinaryWriter writer = new BinaryWriter(filestream))
    12             {
    13 
    14                 writer.Write(str);
    15 
    16             }
    17 
    18         }

      (2)BinaryReader类实现文件的读取操作:

     1 public string DoRead()
     2         {
     3             /*文件在项目中的相对于根目录的位置*/
     4             string Relative_path = "/Binary/first_" + DateTime.Today.ToString("yy-MM-dd") + ".dat";
     5 
     6             /*获取项目的根目录*/
     7             string Full_path = AppDomain.CurrentDomain.BaseDirectory + Relative_path;
     8 
     9             /*存储结果*/
    10             string Read_text = string.Empty;
    11 
    12             FileStream filestream = new FileStream(Full_path, FileMode.Open, FileAccess.Read);
    13 
    14             using (BinaryReader reader = new BinaryReader(filestream))
    15             {
    16 
    17                 /*判断是否读到结尾处*/
    18                 while (reader.PeekChar() != -1)
    19                 {
    20 
    21                     Read_text += reader.ReadString();
    22 
    23                 }
    24 
    25                 return Read_text;
    26             }
    27 
    28         }

       

  • 相关阅读:
    【摘】DB2程序性能
    动态html标签textarea的readOnly属性(JavaScript)
    Html和Xml 文件中的特殊字符 需要转义【转】
    ping的通telnet不正常 服务器之间连接不稳定
    AJAX 和 JSP 10.5(转)实现进度条【转】
    RedHat上部署was7.0
    JPPF 在Windows Server 2008R2上的配置
    银联贷记卡账务账务计算说明
    mybatis源码分析
    使用Neo4j的apoc插件,实现数据从MySQL抽取到Neo4j
  • 原文地址:https://www.cnblogs.com/SunshineAgain/p/5703480.html
Copyright © 2011-2022 走看看