《C#.net程序设计》(资料全集)c#8.ppt
文本预览下载声明
第八章流、文件、XML和配置文件 ;本章主要内容;流Stream类;FileStream类;Append;读写方式FileAccess枚举型列表;using System;
using System.IO;
class FSRead{
public static void Main() {
string inPath = @..\..\Program.cs;//输入文件名
FileStream infs = new FileStream(inPath, FileMode.Open); //创建已存在文件流
string outPath = @output.txt;//输出文件名
FileStream outfs = new FileStream(outPath, FileMode.Create); //创建新文件流
long nBytes = infs.Length;//输入文件流长度
//每次读字节长度取读文件字节数最大值(整型最大值)与文件流长度的较小值,
int readLen = (int)Math.Min(int.MaxValue, nBytes);
byte[] ByteArray = new byte[readLen];
int nBytesRead;
do{//当输入文件流长度大于整型最大值时,一次无法读完
nBytesRead = infs.Read(ByteArray, 0, readLen);//读文件数据
if (nBytesRead == 0) break;//没有数据读入,退出循环
outfs.Write(ByteArray, 0, nBytesRead);//写数据到文件output.txt
} while (nBytesRead 0);
infs.Close();
outfs.Close();
}
};BinaryReader与BinaryWriter类;ReadBoolean ;例:使用BinaryReader,FileStream读写基本数据类型数据到文件,项目BinaryReadWrite代码如下:
class MyStream {
private const string FILE_NAME = Test.data;//文件名
public static void Main(String[] args){// 新建空文件用于写入数据.
FileStream fs = new FileStream(FILE_NAME, FileMode.Create);
BinaryWriter w = new BinaryWriter(fs); //指定关联的FileStream流对象fs
for (int i = 0; i 11; i++){//写入数据到Test.data文件
w.Write(i);//写入整数
w.Write(i.ToString());//写入字符串
}
w.Close();
fs.Close();
fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);// 新建BinaryReader用于读数据.
for (int i = 0; i 11; i++){//从Test.data文件读出整数和字符串
Console.WriteLine(r.ReadInt32()+r.ReadString());
}
r.Close();
fs.Close();
}
};TextReader,StreamReader,StringReader类;下面是TextReader项目的部分代码:
class TextRW{
static void Main() {
TextWriter stringWriter = new StringWriter();
WriteText(stringWriter);
TextReader stringReader =new StringReader(stringWriter.ToString());
ReadText(stringReader);
using (TextWriter streamWriter =new StreamWriter(ErrPathChars.txt))
{
显示全部