微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C# I/O二进制文件

using System;
using System.IO;

namespace BinaryFileApplication {

   class Program {

      static void Main(string[] args) {
         BinaryWriter bw;
         BinaryReader br;
         int i = 25;
         double d = 3.14157;
         bool b = true;
         string s = I am happy;

         //create the file
         try {
            bw = new BinaryWriter(new FileStream(mydata, FileMode.Create));
         } catch (IOException e) {
            Console.WriteLine(e.Message + \n Cannot create file.);
            return;
         }

         //writing into the file
         try {
            bw.Write(i);
            bw.Write(d);
            bw.Write(b);
            bw.Write(s);
         } catch (IOException e) {
            Console.WriteLine(e.Message + \n Cannot write to file.);
            return;
         }
         bw.Close();

         //reading from the file
         try {
            br = new BinaryReader(new FileStream(mydata, FileMode.Open));
         } catch (IOException e) {
            Console.WriteLine(e.Message + \n Cannot open file.);
            return;
         }

         try {
            i = br.ReadInt32();
            Console.WriteLine(Integer data: {0}, i);
            d = br.ReadDouble();
            Console.WriteLine(Double data: {0}, d);
            b = br.ReadBoolean();
            Console.WriteLine(Boolean data: {0}, b);
            s = br.ReadString();
            Console.WriteLine(String data: {0}, s);
         } catch (IOException e) {
            Console.WriteLine(e.Message + \n Cannot read from file.);
            return;
         }
         br.Close();
         Console.ReadKey();
      }
   }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐