c#-文件和流-读写二进制流-简单实验

这段代码演示了如何使用C#的BinaryWriter将浮点数、整数、长整型和字符串写入二进制文件,然后使用BinaryReader读取这些数据。文件操作在`WriteFileUsingBinaryWriter`和`ReadFileUsingBinaryReader`方法中完成,确保数据的准确读写。
摘要由CSDN通过智能技术生成

1.概要

var outputStream = File.Create(binfile);
            using (var write = new BinaryWriter(outputStream)) {
                double d = 47.47;

 write.Write(s);

var inputStream = File.Open(binfile, FileMode.Open);
            using (var reader = new BinaryReader(inputStream)) {
                double d = reader.ReadDouble();

long l = reader.ReadInt64();

2.代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace ConsoleApp11
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            string fileName4 = "test4.txt";
            string f4 = Path.Combine(GetFolderPath(), fileName4);
            WriteFileUsingBinaryWriter(f4);
            ReadFileUsingBinaryReader(f4);
            Console.ReadKey();
        }
        static string GetFolderPath() {
            return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        }
        static void WriteFileUsingBinaryWriter(string binfile) {
            var outputStream = File.Create(binfile);
            using (var write = new BinaryWriter(outputStream)) {
                double d = 47.47;
                int i = 42;
                long l = 987654321;
                string s = "sample";
                write.Write(d);
                write.Write(i);
                write.Write(l);
                write.Write(s);
            }
        }
        static void ReadFileUsingBinaryReader(string binfile) {
            var inputStream = File.Open(binfile, FileMode.Open);
            using (var reader = new BinaryReader(inputStream)) {
                double d = reader.ReadDouble();
                int i = reader.ReadInt32();
                long l = reader.ReadInt64();
                string s = reader.ReadString();
                Console.WriteLine($"d:{d},i:{i},l:{l},s:{s}");
            }
        }
        
    }
}

3.运行结果 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值