【文件属性】:
文件名称:文件和流-金蝶esb企业服务总线7.0用户手册
文件大小:1.82MB
文件格式:PDF
更新时间:2021-06-03 17:07:23
c# 教程
第六章 文件和流
编程语言在如何处理输入/输出问题方面已经经过了很多变革。早期语言,例如 Basic
语言,使用 I/O 语句。后来的语言,例如 C 语言,使用标准的 I/O 库(stdio.h)。在 C++和
Java 语言中,引入了抽象的概念:流。流的概念不仅可用于文件系统,也可用于网络。但
在 C++和 Java 语言中流的概念比较复杂。C#语言也采用了流的概念,但是使用起来要简单
的多。本章介绍 C#语言中,如何处理目录和文件夹,如何处理文件,如何使用流的概念读
写文件。
6.16.16.16.1 用流读写文件用流读写文件用流读写文件用流读写文件
C#把每个文件都看成是顺序的字节流,用抽象类 Stream 代表一个流,可以从 Stream 类
派生出许多派生类,例如 FileStream 类,负责字节的读写,BinaryRead 类和 BinaryWrite 类
负责读写基本数据类型,如 bool、String、int16、int 等等,TextReader类和 TextWriter 类负
责文本的读写。本节介绍这些类的用法。
6.1.16.1.16.1.16.1.1 用 FileStreamFileStreamFileStreamFileStream类读写字节
写字节代码段如下:
byte[] data=new byte[10];
For(int i=0;i<10;i++)
data[i]=(byte)i;
System.IO.FileStream fs=new System.IO.FileStream("g1",FileMode.OpenOrCreate);
fs.Write(data,0,10);
读字节代码段如下:
byte[] data=new byte[10];
System.IO.FileStream fs=new System.IO.FileStream("g1",FileMode.OpenOrCreate);
fs.Seek(-5,SeekOrigin.End);
int n=fs.Read(data,0,10);//n 为所读文件字节数
6.1.26.1.26.1.26.1.2 用BinaryReadeBinaryReadeBinaryReadeBinaryReaderrrr和 BinaryWriteBinaryWriteBinaryWriteBinaryWriterrrr类读写基本数据类
型
C#中除了字节类型以外,还有许多其它基本数据类型,例如,int、bool、float 等等,
读写这些基本数据类型需要使用 BinaryReader 和 BinaryWriter类。写 int 类型数据代码段如
下:
System.IO.FileStream fs=new System.IO.FileStream("g1",FileMode.OpenOrCreate);
System.IO.BinaryWrite w=new System.IO. BinaryWrite(fs);